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 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 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();
}

你可能感兴趣的:(java,vue.js)