sending file from response to user, Spring REST +

2019-08-09 08:22发布

问题:

I have Spring controller like this:

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public byte[] getFilesInZIP(@RequestParam("filenames[]") String[] filenames){
        byte[] file = service.packFilesToZIPArchiveAndReturnAsByteArray(filenames);
        return file;
    }

And now when I create frontend, I want to send array containing filenames to the controller and download ZIP archive which contains files I chose.

(To be clear: lets assume that I want to dowload 3 files: a.txt, b.txt and c.txt; I sent AJAX request using jquery with array: ['a.txt', 'b.txt', 'c.txt'] as ajax data. And now I want spring controller to find these files, pack them to ZIP archive and send this archive to me as byte[] in response)

Here is sample jQuery code:

        var tab = ['a.txt', 'b.txt', 'c.txt'];
        jQuery.ajax({
            url: "http://localhost:8080/download",
            type: "GET",
            data: {
                'filenames': tab
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert('problem');
            }
        });

But I have no idea how to handle this response to send this archive ZIP file to the user. When I was trying to do this using 's in HTML everything was okay.

I have done a research but found nothing helpful. There was some jQuery plugin which downloaded the file, but from URL like: localhost/file.txt ; I want my file to be downloaded as I said upper and first, additionally send array with filenames to the controller.

回答1:

I recommend you to use this JS plugin https://github.com/johnculviner/jquery.fileDownload to download the file instead using $.ajax directly. You can find all the official documentation there.

Also, in your controller, you have to take your HttpServletResponse and write the byte[] in the outputstream, and you have to put a cookie in the response to advise the JS plugin (because it needs it)

For example:

@RequestMapping(value = "/download", method = RequestMethod.GET)
    public void getFilesInZIP(@RequestParam("filenames[]") String[] filenames, HttpServletResponse httpServletResponse){
        byte[] file = service.packFilesToZIPArchiveAndReturnAsByteArray(filenames);

        Cookie cookie = new Cookie("fileDownload", "true");
        cookie.setPath("/");

        httpServletResponse.addCookie(cookie);
        httpServletResponse.setContentType("application/zip");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=files.zip");
        httpServletResponse.getOutputStream().write(file);

    }