实现思路:后台程序读取文件,把数据写给浏览器;即输入流读文件,写到浏览器的输出流中
Demo代码:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/zip")
public void zip(HttpServletResponse response) {
response.reset();
response.setContentType("application/multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=test.zip");
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))) {
String content_test_1 = "test_zip_1";
String content_test_2 = "test_zip_2";
zos.putNextEntry(new ZipEntry(content_test_1));
zos.write(content_test_1.getBytes(StandardCharsets.UTF_8));
zos.putNextEntry(new ZipEntry(content_test_2));
zos.write(content_test_1.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
@GetMapping("/tar")
public void tar(HttpServletResponse response) {
response.reset();
response.setContentType("application/multipart/form-data");
response.setHeader("Content-Disposition", "attachment;filename=test.tar");
try (TarArchiveOutputStream tarOps = new TarArchiveOutputStream(new BufferedOutputStream(response.getOutputStream()))){
String content_test_1 = "test_tar_1";
String content_test_2 = "test_tar_2";
TarArchiveEntry entry_1 = new TarArchiveEntry("test_tar_1");
entry_1.setSize(content_test_1.length());
tarOps.putArchiveEntry(entry_1);
tarOps.write(content_test_1.getBytes(StandardCharsets.UTF_8));
tarOps.closeArchiveEntry(); // 需要关闭
TarArchiveEntry entry_2 = new TarArchiveEntry("test_tar_2");
entry_2.setSize(content_test_2.length());
tarOps.putArchiveEntry(entry_2);
tarOps.write(content_test_2.getBytes(StandardCharsets.UTF_8));
tarOps.closeArchiveEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
}