• 如何将文件或者图片压缩成zip文件压缩包


    代码:

    1. @RestController
    2. @RequestMapping("/download")
    3. public class DownloadController {
    4. @GetMapping("/studentWork")
    5. public ResponseEntity downloadStudentWork() {
    6. HttpHeaders headers = new HttpHeaders();
    7. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    8. String encodedFileName = "作品名称-学生姓名.zip";
    9. // StringBuffer stringBuffer = new StringBuffer();
    10. // stringBuffer.append("作品名称"+"-学生姓名.zip");
    11. //
    12. try {
    13. encodedFileName = URLEncoder.encode(encodedFileName, StandardCharsets.UTF_8.toString());
    14. System.out.println(encodedFileName);
    15. } catch (UnsupportedEncodingException e) {
    16. e.printStackTrace();
    17. }
    18. headers.setContentDispositionFormData("attachment", encodedFileName);
    19. StreamingResponseBody responseBody = outputStream -> {
    20. try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
    21. // 假设这是学生的作品海报图片文件流
    22. InputStream imgStream = getStudentPosterData();
    23. addToZip(zipOut, imgStream, "作品封面.jpg");
    24. // 添加更多附件,如果有的话
    25. zipOut.finish();
    26. } catch (IOException e) {
    27. // 处理异常
    28. }
    29. };
    30. return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
    31. }
    32. private void addToZip(ZipOutputStream zipOut, InputStream inputStream, String fileName) throws IOException {
    33. ZipEntry zipEntry = new ZipEntry(fileName);
    34. zipOut.putNextEntry(zipEntry);
    35. byte[] buffer = new byte[1024];
    36. int bytesRead;
    37. while ((bytesRead = inputStream.read(buffer)) != -1) {
    38. zipOut.write(buffer, 0, bytesRead);
    39. }
    40. zipOut.closeEntry();
    41. inputStream.close();
    42. }
    43. // 获取学生作品海报图片数据的示例方法
    44. private InputStream getStudentPosterData() throws FileNotFoundException {
    45. FileInputStream inputStream = new FileInputStream("C:\\Users\\admin\\Pictures\\Saved Pictures\\微信图片_20230914093742.png");
    46. String filePath = "C:\\Users\\admin\\Pictures\\Saved Pictures\\微信图片_20230914093742.png";
    47. File file = new File(filePath);
    48. if (file.exists()){
    49. System.out.println("文件存在");
    50. }else {
    51. throw new RuntimeException();
    52. }
    53. return inputStream;
    54. }

    示例:

  • 相关阅读:
    笔记本搜不到WiFi是什么原因
    也太全了吧,分享16种机器学习类别特征处理方法
    2024 RubyMine 激活,分享几个RubyMine 激活的方案
    无人机飞手教员组装、调试高级教学详解
    SCALA基础
    node.js+mysql+vue.js+vuex+echarts+elementui全栈后台管理系统
    节能灯与led灯哪个对眼睛好?分享专业护眼的led灯
    解决报错:npm ERR! code 1
    互联网金融P2P主业务场景自动化测试
    Hyperledger Besu环境搭建(Linux)
  • 原文地址:https://blog.csdn.net/XikYu/article/details/132904618