在Rest API中,需要构建ZIP并下载到客户端系统

问题描述 投票:0回答:1

我有一个REST API,它需要:1。从对象创建一些Json文件2.压缩所有这些文件3.下载到客户端系统 - 无论谁访问URL。

我可以执行第1步和第2步,但是在执行第3步时,它会下载到我的服务器,但不会下载到客户端。目前我在我的本地尝试,稍后此代码移至AWS,不确定它是否也将下载到服务器或客户端本地:

第3步的代码:

public void downloadZip(String zipFileName)
{
    File file = new File(zipFileName);
    if(!file.exists()){
        System.out.println("file not found");
    }

    OutputStream out = null;
    try
    {
        out = new FileOutputStream("test_"+zipFileName);
        FileInputStream in = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
java rest file download zip
1个回答
0
投票

试试这个,使用内容类型application/zip

 if(file.exists()){
        byte[] arr = FileUtils.readFileToByteArray(file);
        return ResponseEntity.ok().contentLength(arr.length)
                        .header(HttpHeaders.CONTENT_TYPE, "application/zip")
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
                        .body(arr);
} else {
        return ResponseEntity.notFound().build();
}
© www.soinside.com 2019 - 2024. All rights reserved.