初步封装
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package com.seeyon.apps.assetstenant.file;
|
||||
|
||||
import com.seeyon.ctp.common.AppContext;
|
||||
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
|
||||
import com.seeyon.ctp.common.filemanager.manager.FileManager;
|
||||
import com.seeyon.ctp.common.po.filemanager.Attachment;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
|
||||
|
||||
public class FileHandlerService {
|
||||
|
||||
private AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
|
||||
private FileManager fileManager = (FileManager) AppContext.getBean("fileManager");
|
||||
|
||||
public void handleFile(String refId, HttpServletResponse response) throws Exception {
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
Attachment attachment = attachmentManager.getAttachmentByFileURL(Long.valueOf(refId));
|
||||
inputStream = fileManager.getFileInputStream(attachment.getFileUrl());
|
||||
|
||||
// ⭐ 关键:重置
|
||||
response.reset();
|
||||
|
||||
// ⭐ 必须设置类型
|
||||
response.setContentType("application/octet-stream");
|
||||
|
||||
// ⭐ 文件名处理
|
||||
String encodedFileName = URLEncoder.encode(attachment.getFilename(), "UTF-8")
|
||||
.replaceAll("\\+", "%20");
|
||||
|
||||
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
|
||||
response.setHeader(
|
||||
"Content-Disposition",
|
||||
"attachment; filename=\"" + attachment.getFilename() + "\"; filename*=UTF-8''" + encodedFileName
|
||||
);
|
||||
|
||||
// ⭐ 输出流
|
||||
OutputStream outputStream = response.getOutputStream();
|
||||
|
||||
byte[] buffer = new byte[2048];
|
||||
int len;
|
||||
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, len);
|
||||
}
|
||||
|
||||
outputStream.flush();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace(); // ❗不要吞异常
|
||||
} finally {
|
||||
try {
|
||||
if (inputStream != null) inputStream.close();
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user