Java实现将word文件打包成zip,并通过浏览器下载zip文件

下载思路:在后端将 ZIP 文件读取为字节数组,然后将字节数组作为响应体返回给前端,前端再将字节数组保存为文件。前端将 responseType 设置为 'arraybuffer',以确保正确处理字节数组的响应。这样,您将能够下载正确的 ZIP 文件并在本地打开它。

前端代码:

vue文件的js里的methods代码如下:(代码当中的方法名可以忽略,我是将之前导出word的方法直接测试的,所以方法名没改)

handleExports(masterid, domain) {				     
				  let params = {
				    masterid: masterid,
				    domain: domain,   //获取文件名
				  };
				
				  exportNewWord(params, { custom: { auth: true } }).then((res) => {
				    console.log(res.msg);
				    let fileUrl = res.msg;
				    if (fileUrl == '1') {
				      this.$message.success("文件下载失败!请联系管理员!");
				      return false;
				    } else {
				      let fileName = fileUrl.substring(fileUrl.lastIndexOf("\\") + 1, fileUrl.length);
				      params = {
				        fileUrl: fileUrl,
				      };
                    //将 responseType 设置为 'arraybuffer',以确保正确处理字节数组的响应
				      downLoadWord(params, { custom: { auth: true }, responseType: 'arraybuffer' }).then(response => {
				        let blob = new Blob([response]);
				        let downloadElement = document.createElement('a');
				        let href = window.URL.createObjectURL(blob);
				        downloadElement.href = href;
				        downloadElement.setAttribute('download', fileName);
				        document.body.appendChild(downloadElement);
				        downloadElement.click();
				        document.body.removeChild(downloadElement);
				        window.URL.revokeObjectURL(href);
				      });
				    }
				  });
				},

后端java代码:

@PostMapping("/exportNewWord")
       public AjaxResult exportNewWord(@RequestBody Map<String, Object> params,  HttpServletResponse response) {
            //原word文档
            String fileName = "abc";
            String tempDir = "将zip放在需要压缩的文件同级目录";
            File outFile = new File(tempDir,fileName+".doc");

        //将word文件压缩成zip文件
            String zipFileName = fileName + ".zip";
            String zipFilePath = tempDir + zipFileName;

            File zipFile = new File(zipFilePath);
          try{
            if(zipFile.exists()) {
                if (zipFile.isDirectory()) {
                    FileUtils.deleteDirectory(zipFile);
                } else {
                    zipFile.delete();
                }
            }
            FileOutputStream fos = new FileOutputStream(zipFilePath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry ze = new ZipEntry(fileName+".doc");

            zos.putNextEntry(ze);
            FileInputStream fis = new FileInputStream(outFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            fis.close();
            zos.flush();
            zos.close();
            fos.close();
            System.out.println(zipFile.length());
            return AjaxResult.success(zipFilePath);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success("1");
    }

@PostMapping("/downLoadWord")
    public void download(@RequestBody Map<String, Object> params,HttpServletResponse response) throws Exception {
        String fileUrl = params.get("fileUrl").toString();
        File file = new File(fileUrl);

        String zipFileName = file.getName();
        String zipFilePath = fileUrl;

        FileInputStream fis = new FileInputStream(file);

        // 创建输出流
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[(int) file.length()];

        fis.read(buffer);
        fis.close();

        // 设置响应头
        response.setContentType("application/zip");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(zipFileName, "UTF-8"));
        out.write(buffer);
        out.flush();
        out.close();

        //删除服务器上的临时文件
        File deleteFile = new File(fileUrl);
        deleteFile.delete();
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值