1. 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "folder.zip");
// 使用ResponseEntity.ok()创建ResponseEntity,并将StreamingResponseBody和响应头作为参数
return ResponseEntity.ok().headers(headers).body(responseBody);
2.这段代码设置响应头在浏览器中下载;
@Controller
public class DownloadController {
@GetMapping("/download")
@ResponseBody
public ResponseEntity<StreamingResponseBody> download() throws IOException {
// 要打包的文件夹路径
String folderPath = "C:/java/folder/";
// 创建临时文件,用于存储生成的zip文件
File tempFile = File.createTempFile("temp", ".zip");
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(tempFile);
// 创建压缩输出流
ZipOutputStream zos = new ZipOutputStream(fos);
// 调用递归方法进行文件夹压缩
zipFolder(folderPath, "", zos);
// 关闭压缩输出流和文件输出流
zos.close();
fos.close();
// 创建StreamingResponseBody,将文件输出流的内容写入输出流
StreamingResponseBody responseBody = output -> {
FileInputStream fis = new FileInputStream(tempFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
fis.close();
};
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "folder.zip");
// 使用ResponseEntity.ok()创建ResponseEntity,并将StreamingResponseBody和响应头作为参数
return ResponseEntity.ok()
.headers(headers)
.body(responseBody);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
// 删除临时文件
tempFile.delete();
// 删除文件夹
File folder = new File(folderPath);
deleteFolder(folder);
}
}
// 递归压缩文件夹的方法,同上例
// ...
// 删除文件夹的递归方法
private void deleteFolder(File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
deleteFolder(file);
}
}
}
folder.delete();
}
}
标签:浏览器,File,headers,响应,文件夹,ResponseEntity,new,folder,下载
From: https://www.cnblogs.com/codeLearn/p/17966796