如何发送动态生成的zip文件以在js中下载?

时间:2019-02-07 18:32:50

标签: javascript angularjs zipfile

我试图通过添加文件路径中的文件列表来生成zip文件。 使用zipOutputStream创建zip并将其发送到javascript以单击下载文件。 我尝试了各种方法来执行此操作,但是找不到解决方案。有人可以帮忙吗?我是Javascript侧编码的新手。

以下是我要执行的操作:

控制器代码:

@RequestMapping(value="/logsDownload", method=RequestMethod.POST)
    @Produces("application/zip")
    public @ResponseBody ResponseEntity <byte[]> zipFiles(Model model,@RequestBody String component,HttpServletRequest request) throws IOException{

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
        ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
        String logFileLocation = "";
        ResponseEntity<byte[]> response = null;
        try {
            logFileLocation = devtestSupportProject.fetchLogs(component); // based on the component the file path will be decided
            File dir = new File(logFileLocation);
            File[] files = dir.listFiles();
            for (File file : files) {
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                FileInputStream fileInputStream = new FileInputStream(file);
                IOUtils.copy(fileInputStream, zipOutputStream);
                fileInputStream.close();
                zipOutputStream.closeEntry();
            }

            if (zipOutputStream != null) {
                zipOutputStream.finish();
                zipOutputStream.flush();
                zipOutputStream.close();
            }
            bufferedOutputStream.close();
            byteArrayOutputStream.close();
            byte[] zipByteArray = byteArrayOutputStream.toByteArray();
            response = new ResponseEntity<byte[]>(zipByteArray, HttpStatus.OK);
        }catch(Exception exp) {
            logger.error(exp.getMessage(),exp);
            byte[] error = exp.getMessage().getBytes();
            response = new ResponseEntity<byte[]>(error, HttpStatus.SERVICE_UNAVAILABLE);       
        return response;
    }

JavaScript代码:

$http.post("logsDownload",$scope.component, {responseType:'arraybuffer'}).then(function successCallback(response) {
                var blob = new blob([response], {'type':"application/zip"});
                var fileUrl = window.URL.createObjectURL(file);
                var filename = "logs.zip";
                var element = document.createElement("a");
                element.style.display = 'none';
                document.body.appendChild(element);
                element.href = fileURL;
                element.download = fileName;
                document.body.removeChild(element);             
            });

0 个答案:

没有答案