package com.vci.ubcs.resource.utils;
|
|
import com.vci.ubcs.resource.bo.FileObjectBO;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.io.IOUtils;
|
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaTypeFactory;
|
|
import javax.servlet.http.Cookie;
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.FileInputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.URLEncoder;
|
|
/**
|
* 下载文件的工具
|
* @author weidy
|
* @date 2023/6/9
|
*/
|
@Slf4j
|
public class FileDownloadUtil {
|
|
/**
|
* 下载文件
|
* @param response 响应对象
|
* @param fileObjectBO 文件的信息,包含文件的输入流
|
* @throws IOException 下载异常会抛出
|
*/
|
public static void downloadFile(HttpServletResponse response, FileObjectBO fileObjectBO) throws IOException {
|
downloadFile(response,fileObjectBO,true);
|
}
|
|
/**
|
* 下载文件
|
* @param response 响应对象
|
* @param fileObjectBO 文件的信息,包含文件的输入流
|
* @param closeInputStream 是否关闭流
|
* @throws IOException 下载出错的时候抛出异常
|
*/
|
public static void downloadFile(HttpServletResponse response, FileObjectBO fileObjectBO,boolean closeInputStream) throws IOException {
|
MediaType mediaType = MediaTypeFactory.getMediaType(fileObjectBO.getBucketName() + "." + fileObjectBO.getFileExtension()).orElse(MediaType.APPLICATION_OCTET_STREAM);
|
// 设置强制下载不打开
|
response.setContentType(mediaType.toString()+";application/force-download;charset=UTF-8");
|
try{
|
String fileName = URLEncoder.encode(fileObjectBO.getName() + "." + fileObjectBO.getFileExtension(), "UTF8");
|
response.addHeader("Content-Disposition", "attachment;filename="+ fileName+ ";filename*=utf-8''");
|
}catch(Exception e){
|
if(log.isErrorEnabled()){
|
log.error("设置文件的名称到响应流的时候出错",e);
|
}
|
}
|
response.setCharacterEncoding("UTF-8");
|
Cookie cookie = new Cookie("fileDownload", "true");
|
cookie.setPath("/");
|
response.addCookie(cookie);
|
if(closeInputStream) {
|
try (InputStream ins = (fileObjectBO.getInputStream() != null ? fileObjectBO.getInputStream() : new FileInputStream(fileObjectBO.getFileLocalPath()))) {
|
IOUtils.copy(ins, response.getOutputStream());
|
} catch (IOException e) {
|
//有可能客户端的链接
|
if (log.isErrorEnabled()) {
|
log.error("写入文件到响应流出错", e);
|
}
|
throw e;
|
}
|
}else{
|
try {
|
InputStream ins = (fileObjectBO.getInputStream() != null ? fileObjectBO.getInputStream() : new FileInputStream(fileObjectBO.getFileLocalPath()));
|
IOUtils.copy(ins, response.getOutputStream());
|
} catch (IOException e) {
|
//有可能客户端的链接
|
if (log.isErrorEnabled()) {
|
log.error("写入文件到响应流出错", e);
|
}
|
throw e;
|
}
|
}
|
}
|
}
|