springboot将文件响应给前端
·
获取当前项目路径
System.out.println(System.getProperty("user.dir"));
将文件放入响应流
/**
* 响应体加入文件流
*
* @param response
* @param filePath 文件从盘符开始的完整路径
*/
public static void buildExcelDocument(HttpServletResponse response, String filePath) {
log.debug("文件流filePath:" + filePath);
//该方法是判断字符串中是否有子字符串。如果有则返回true,如果没有则返回false。
if (filePath.contains("%")) {
try {
filePath = URLDecoder.decode(filePath, "UTF-8");
System.out.println(filePath);
} catch (UnsupportedEncodingException e) {
log.debug("响应流解码错误:" + e.toString());
}
}
ServletOutputStream out = null;
FileInputStream in = null;
try {
in = new FileInputStream(new File(filePath));
String[] dir = filePath.split("/");
String fileName = dir[dir.length - 1];
String[] array = fileName.split("[.]");
String fileType = array[array.length - 1].toLowerCase();
//设置文件ContentType类型、图片类型
if ("jpg,jepg,gif,png".contains(fileType)) {
response.setContentType("image/" + fileType);
//pdf类型
} else if ("pdf".contains(fileType)) {
response.setContentType("application/pdf");
} else {
//自动判断下载文件类型
response.setContentType("multipart/form-data");
}
out = response.getOutputStream();
// 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
response.setStatus(200);
} catch (FileNotFoundException e) {
log.error("error:FileNotFoundException:" + e.toString());
} catch (Exception e) {
log.error("error:" + e.toString());
} finally {
try {
assert out != null;
out.close();
in.close();
} catch (NullPointerException e) {
log.error("close error:NullPointerException:" + e.toString());
} catch (Exception e) {
log.error("close error:Exception:" + e.toString());
}
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)