写一个springmvc文件下载
时间: 2024-01-16 12:03:44 浏览: 23
@Controller
public class FileDownloadController {
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取文件路径
String filePath = "your_file_path_here";
// 获取文件名
String fileName = "your_file_name_here";
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 读取文件
InputStream inputStream = new FileInputStream(filePath);
// 写入响应流
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// 关闭流
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
在上面的代码中,你需要替换文件路径和文件名。当请求 /download 时,它会将文件作为响应体返回,浏览器会自动下载该文件。