@Slf4j
public class FileUtil {
/**
* 文件转流
* @param file
* @param fileName
* @param response
* @return
* @throws Exception
*/
public static Object saveResponseFile(File file, String fileName, HttpServletResponse response, Boolean isInLine) throws Exception {
setContentType(fileName, response);
response.setCharacterEncoding("UTF-8");
String headerType = "attchement";
if (isInLine != null && isInLine) {
//"inline"
headerType = "inline";
}
response.setHeader("Content-Disposition", headerType + ";filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream out = null;
FileInputStream fis = null;
try {
//获取要下载的文件输入流
fis = new FileInputStream(file);
int len = 0;
//通过response对象获取outputStream流
out = response.getOutputStream();
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
} finally {
try {
if (out != null)
out.close();
if (fis != null) {
fis.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return true;
}
public static void setContentType(String fileName, HttpServletResponse response) {
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(Locale.ROOT);
switch (suffix) {
case "pdf":
response.setContentType("application/pdf");
return;
case "jpg":
response.setContentType("image/jpeg");
return;
case "png":
response.setContentType("image/png");
return;
default:
response.setContentType("application/octet-stream");
return;
}
}
}
== 使用:==
FileUtil.saveResponseFile(new File(resultMap.get(“path”)),resultMap.get(“fileName”),response,false);