package com.bilibili.juc.controller;
import cn.hutool.core.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("download")
public class DownloadController {
private final Logger logger = LoggerFactory.getLogger(DownloadController.class);
@RequestMapping("/downloadFile")
public boolean download(String path, HttpServletResponse response) {
boolean flag = false;
try {
path = "D:\\upload\\FA400ED0-F46F-4591-8566-AF553168530C.doc";
// path是指欲下载的文件的路径。
File file = new File(path);
if (!FileUtil.isEmpty(file)) {
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
flag = true;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return flag;
}
}
java下载文件工具类
最新推荐文章于 2023-11-21 22:01:39 发布