【问题标题】:Downloaded zip file is corrupted下载的 zip 文件已损坏
【发布时间】:2014-04-30 13:49:10
【问题描述】:

我正在尝试让用户使用以下代码从服务器下载 zip 文件: 服务器:

 @RequestMapping(value = "/get-shape-file", method = RequestMethod.GET)
public void getFile( HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader rd = new BufferedReader (new FileReader("/shape/lastlyExportedFileName"));    
    String fileName = rd.readLine().trim();
    rd.close();
    try {            
        OutputStream myOut = null;
        FileInputStream fileInputStream = null;
        File downzip = new File("/shape/" + fileName);

        response.setContentType("TEXT/HTML");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentLength((int) downzip.length());
        System.out.println("length  " + (int) downzip.length());
        //READ DATA FROM FILE

        byte[] dataRead = new byte[(int) downzip.length()];
        fileInputStream = new FileInputStream(downzip);
        fileInputStream.read(dataRead, 0, (int) downzip.length());
        //WRITE DATA TO OUTFILE
        myOut = response.getOutputStream();
        myOut.write(dataRead);

        if (fileInputStream != null) {
            fileInputStream.close();
        }

      } catch (IOException ex) {
        logger.error("Error writing file to output stream. Filename was '" + fileName + "'");
        throw new RuntimeException("IOError writing file to output stream");
      }
}

客户:

 $.ajax({
    url: 'url-to-the-method/get-shape-file',
    type: 'GET',
    success: function(shape) {
        console.log(shape);
        var a = document.createElement('a');
        a.href = 'data:attachment/zip,' + shape;
        a.target = '_blank';
        a.download = 'exported-shape-file.zip';
        document.body.appendChild(a);
        a.click();
    },
    error: function(data) {
        Message.error("Could not download shapefile");
    }
});       

但下载的文件已损坏。大小大于应有的大小,当尝试在存档管理器中打开文件时,也会显示此消息: zipinfo:在 /home/tengiz/Downloads/exported-shape-file (1).zip 之一中找不到 zipfile 目录或 /home/tengiz/Downloads/exported-shape-file (1).zip.zip,找不到 /home/tengiz/Downloads/exported-shape-file (1).zip.ZIP,句号。

【问题讨论】:

标签: java javascript spring-mvc zip


【解决方案1】:

我解决了这个问题,原来问题出在客户端而不是服务器端。 在客户端,我试图将响应附加到 href 但由于响应包含字节码,它丢失了一些重要字符。你需要做的只是创建一个带有控制器方法链接的标签,所以你不需要像这样的任何 ajax 请求:

        var a = document.createElement('a');
        a.href = '/url-to/get-shape-file';
        document.body.appendChild(a);
        a.click();    

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多