导出一个文件
程序员文章站
2024-03-20 21:01:04
...
导出一个文件
响应对象指定响应头和内容类型,注意文件名要加文件后缀
@Autowired(required = false)
private HttpServletResponse response;
public void exportExcelFile() throws IOException {
File file = new File("文件路径");
InputStream inputStream = new FileInputStream(file);
String fileName = "文件名.xlsx";
response.setContentType("application/octet-stream");//.xlsx格式
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
// response是HttpServletResponse的实例对象
ServletOutputStream outputStream = response.getOutputStream();
byte[] arr = new byte[1024 * 4];
int len;
while ((len = inputStream.read(arr)) != -1) {
outputStream.write(arr, 0, len);
}
outputStream.close();
inputStream.close();
}