簡體   English   中英

在服務器上創建Zip文件並使用java下載該zip文件

[英]Zip file created on server and download that zip, using java

我有以下代碼從mkyong到本地的zip文件。 但是,我的要求是在服務器上壓縮文件並需要下載。 任何人都可以幫忙。

代碼寫入zipFiles:

public void zipFiles(File contentFile, File navFile)
{
    byte[] buffer = new byte[1024];

    try{
        // i dont have idea on what to give here in fileoutputstream
        FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze= new ZipEntry(contentFile.toString());
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream(contentFile.toString());

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();
        zos.closeEntry();

        //remember close it
        zos.close();

        System.out.println("Done");

    }catch(IOException ex){
       ex.printStackTrace();
    }
}

我可以在fileoutputstream中提供什么? contentfile和navigationfile是我從代碼創建的文件。

如果您的服務器是一個servlet容器,只需編寫一個HttpServlet來進行壓縮並為該文件提供服務。

您可以將servlet響應的輸出流傳ZipOutputStream的構造函數,zip文件將作為servlet響應發送:

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

在壓縮之前不要忘記設置響應mime類型,例如:

response.setContentType("application/zip");

全貌:

public class DownloadServlet extends HttpServlet {

    @Override
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=data.zip");

        // You might also wanna disable caching the response
        // here by setting other headers...

        try ( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()) ) {
            // Add zip entries you want to include in the zip file
        }
    }
}

嘗試這個:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

    // Get your file stream from wherever.
    InputStream myStream = someClass.returnFile();

    // Set the content type and attachment header.
    response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
    response.setContentType("txt/plain");

    // Copy the stream to the response's output stream.
    IOUtils.copy(myStream, response.getOutputStream());
    response.flushBuffer();
}

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM