茶凉_ 2023-06-05 16:56 采纳率: 36.8%
浏览 46
已结题

java以zip方式下载文件报错,解压时显示数据损坏

将word文件以压缩包的形式,在浏览器下载。实现报错:解压下载的zip文件,显示数据损坏,如图

img

详细代码如下:

 @PostMapping("/exportNewWord")
    public AjaxResult exportNewWord(@RequestBody Map<String, Object> params,  HttpServletResponse response) {
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            String  masterid  = params.get("masterid").toString();
            String  domain  = params.get("domain").toString();
            Map<String, Object> map = new HashMap<>();
            Applysourcepooldetail detailQuery = new Applysourcepooldetail();
            detailQuery.setMaterid(Long.valueOf(masterid));
            List<Applysourcepooldetail> list = applysourcepooldetailService.selectApplysourcepooldetailList(detailQuery);
            if (list.size()>0) {
                for (int i = 0; i < list.size(); i++) {
                    Applysourcepooldetail detail = list.get(i);
                    if(detail.getInputvalue().contains("</")&&detail.getInputvalue().contains("/>")&&detail.getInputvalue().contains("src=")){
                        StringBuilder stringBuilder=new StringBuilder(detail.getInputvalue());
                        if (!stringBuilder.substring(1,7).contains("<img")) {
                            stringBuilder.insert(3, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                        }
                        detail.setInputvalue(stringBuilder.toString());
                        map.putAll(this.getData(map,detail,domain));
                    }else{
                        map.put(detail.getInputfield(), detail.getInputvalue());
                    }
                }
            }
            WordHtmlGeneratorHelper.handleAllObject(map);
            Template t = null;
            String filePath="";
            if(domain.contains("工业互联网平台服务商")){
                filePath = RuoYiConfig.getProfile() + "/template/exportWord.ftl";
                configuration.setDirectoryForTemplateLoading(new File(filePath).getParentFile());//模板文件所在路径
                t = configuration.getTemplate("exportWord.ftl","UTF-8"); //获取模板文件
            }else if(domain.contains("两化融合")){
                filePath = RuoYiConfig.getProfile() + "/template/exportLhrhWord.ftl";
                configuration.setDirectoryForTemplateLoading(new File(filePath).getParentFile());//模板文件所在路径
                t = configuration.getTemplate("exportLhrhWord.ftl","UTF-8"); //获取模板文件
            }else if(domain.contains("工业互联网解决方案服务商")){
                filePath = RuoYiConfig.getProfile() + "/template/resolveWord.ftl";
                configuration.setDirectoryForTemplateLoading(new File(filePath).getParentFile());//模板文件所在路径
                t = configuration.getTemplate("resolveWord.ftl","UTF-8"); //获取模板文件
            }

            File outFile = null;
            String fileName = domain;
            // s为当前用户桌面所在路径
            String tempDir = RuoYiConfig.getProfile()+File.separator;
//            fileName = fileName+".doc";
            outFile = new File(tempDir,fileName+".doc");
            if(!outFile.exists()){
                outFile.getParentFile().mkdirs();
            }
            Writer out = null;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
            t.process(map, out); //将填充数据填入模板文件并输出到目标文件
            out.close();
            /*压缩*/
            String zipFileName = fileName + ".zip";
            String zipFilePath = tempDir + zipFileName;
            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);
            }
            fis.close();
            zos.closeEntry();
            zos.flush();
            zos.close();
            fos.close();
            //删除服务器上的临时文件
        File deleteFile = new File(tempDir+fileName+".doc");
        deleteFile.delete();
            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 in = null;
        OutputStream out = null;
        try {
            //获取文件名
            String filename = zipFileName;
            filename = new String(filename.getBytes("iso8859-1"), "UTF-8");

            String downloadpath = zipFilePath;
            //设置响应头,控制浏览器下载该文件
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            //读取要下载的文件,保存到文件输入流
            in = new FileInputStream(downloadpath);
            //创建输出流
            out = response.getOutputStream();
            //缓存区
            byte buffer2[] = new byte[1024];
            int len2 = 0;
            //循环将输入流中的内容读取到缓冲区中
            while ((len2 = in.read(buffer2)) > 0) {
                out.write(buffer2, 0, len2);
                out.flush();
            }
        } finally {
            //关闭
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
        //删除服务器上的临时文件
//        File deleteFile = new File(fileUrl);
//        deleteFile.delete();
        //删除服务器上的压缩文件
        File deleteZipFile = new File(zipFilePath);
        deleteZipFile.delete();
    }

有没有人指导下

  • 写回答

3条回答 默认 最新

  • 茶凉_ 2023-06-07 09:06
    关注

    后端改完的代码如下:

    /*压缩文件*/
                String zipFileName = fileName + ".zip";
               String zipFilePath = tempDir + zipFileName;
               File zipFile = new File(zipFilePath);
               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();
               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();
    }
    

    前端请求代码需要将
    将 responseType 设置为 'arraybuffer',以确保正确处理字节数组的响应。
    详情可以参考我的创作内容里面有,希望有帮助。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 6月7日
  • 已采纳回答 6月7日
  • 创建了问题 6月5日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog