文件下载 简单案例
package com.example.demo.controller;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class FileDownloadController {
private static final int BUFFER_SIZE = 4096;
@GetMapping("/download/{fileName:.+}")
public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
// 获取文件名和路径
String filePath = "D:\\" + fileName;
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
// 设置响应属性
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
// 写入输出流
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}
标签:文件,String,int,inputStream,案例,file,import,response,下载
From: https://www.cnblogs.com/caoxuekun/p/17476135.html