在Java Spring MVC中下载zip文件Ajax响应

时间:2019-03-29 09:35:39

标签: javascript java ajax spring-mvc

我正在尝试将多个文件下载为zip文件,我正在将带有表单数据的AJAX请求发布到服务器,该服务器压缩文件并将其返回给客户端下载,并使用以下代码:< / p>

function downloadDocs(arrays) {
    console.log("Call download");       
    var text = JSON.stringify(arrays);
    $("#selectedList").val(text);
    var formData = new FormData($("#formSelectionFiles")[0]);
    formData.append("candidateId", $("#candidateId").val());
    $.ajax({
        type : "POST",          
        url : "${contextPath}/ajax/candidate/onboarding/multidownload?data=",
        contentType: false,
        processData: false,
        data : formData,            
        success : function(data) {              
            var blob = new Blob([data], {type: "application/octet-stream"});
            //URL.createObjectURL(blob)
            saveAs(blob, "download.zip");
            console.log("SUCCESS : " + data);               
        },
        error : function(e) {
            console.log("ERROR : ", e);
        }
    });
}

我的控制器到映射URL:

@RequestMapping(value = "/ajax/candidate/onboarding/multidownload", method = RequestMethod.POST
        , produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)

public @ResponseBody byte[] downloadCandidateDoc(HttpServletRequest req, HttpServletResponse res, Long candidateId,
        String selectedList) {
    System.out.println(selectedList);
    if (TextUtils.isEmpty(selectedList)) {
        return null;
    }
    final Type token = (Type) new TypeToken<ArrayList<DownloadItem>>() {
    }.getType();
    final GsonBuilder builder = new GsonBuilder();
    final Gson gson = builder.create();
    final List<DownloadItem> fileList = gson.fromJson(selectedList, token);
    return candidateService.downloadCandidateDocs(res, String.valueOf(candidateId), fileList);
}

我的服务:

public byte[] downloadCandidateDocs(HttpServletResponse res, String id, List<DownloadItem> files) {
    final String candidateDir = MediaUtil.getAbsolutePath("upload_candidate", id);
    List<String> fileList = new ArrayList<>();
    if (files != null && !files.isEmpty()) {
        for (DownloadItem str : files) {
            System.out.println("file name: " + str.getUrl());
            fileList.add(new File(candidateDir, str.getUrl()).getAbsolutePath());
        }
    }

    try {
        return FileStreamUtil.zipfiles(fileList);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

}

此代码用于生成zip文件:

    public static byte[] zipfiles(List<String> files) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    byte bytes[] = new byte[2048];
    for (String fileName : files) {
        File fileToZip = new File(fileName);
        FileInputStream fis = new FileInputStream(fileName);
        ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
        zos.putNextEntry(zipEntry);
        int bytesRead;
        while ((bytesRead = fis.read(bytes)) != -1) {
            zos.write(bytes, 0, bytesRead);
        }
        zos.closeEntry();
        fis.close();
        fis.close();
    }
    zos.close();
    return baos.toByteArray();
}

这是我在输出流中收到的结果:

enter image description here

0 个答案:

没有答案