@OpLog(name = "附件下载")
@ApiOperation(value = "附件下载")
@PostMapping("/download")
public void download(String path,String fileName,HttpServletResponse response) {
try {
File file = new File(path);
log.info(file.getPath());
// 获取文件名
//String filename = file.getName();
// 获取文件后缀名
String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
log.info("文件后缀名:" + ext);
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
// response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
// response.addHeader("Access-Control-Allow-Origin", "*");
// 将文件写入输出流
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
文件下载例子
最新推荐文章于 2024-09-08 21:42:31 发布
该代码段展示了如何在Java中创建一个处理文件下载的API。通过接收文件路径和名称,它读取文件内容,设置HTTP响应头,包括Content-Disposition和Content-Length,然后将文件写入到HTTP响应的输出流中,以供客户端下载。
摘要由CSDN通过智能技术生成