Download image in spark java

时间:2016-02-12 22:03:34

标签: java spark-java

I followed the discussion on spark github page as well as stack overflow to understand how to upload files using spark and apache file uploads.

Now I want the user to have an option to download the image on click.

For example my uploaded files get stored in /tmp/imageName.jpg on the server.

On the client side i want to give the user an option to download the file when the user clicks in the hyperlink.

UNIQUE

When the user click on the hyperlink I will call the function with the file path but can't understand how to send the image in response.

I do know that HTML5 has download attribute but that would require the files to be kept in public folder on the server which is not possible.

I went through the previous similar question add tried to replicate for my scenario without success

How can I send a PNG of a QR-code in a HTTP response body (with Spark)?

How download file using java spark?

Edit: I did follow the link provided in the answer to force download the image, but using response.raw() i'm not able to get the response

<a href="/image/path">click here</a> 

Edit 2:

I'm not sure what is the difference between using response.body () vs response.raw().someFunction(). In either case I can seem to send the data back in response. Even if i write a simple response.body("hello") it doesn't reflect in my response.

Is there a difference in how a file would be read as opposed to an image ? Exampling using ImageIO class ?

1 个答案:

答案 0 :(得分:4)

以下是适合我的解决方案:

<强> Service.java

get(API_CONTEXT + "/result/download", (request, response) -> {

        String key = request.queryParams("filepath");
        Path path = Paths.get("/tmp/"+key);
        byte[] data = null;
        try {
            data = Files.readAllBytes(path);
        } catch (Exception e1) {

            e1.printStackTrace();
        }

        HttpServletResponse raw = response.raw();
        response.header("Content-Disposition", "attachment; filename=image.jpg");
        response.type("application/force-download");
        try {
            raw.getOutputStream().write(data);
            raw.getOutputStream().flush();
            raw.getOutputStream().close();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return raw;


   });

Angular Code

$scope.downloadImage= function(filepath) {
         console.log(filepath);
         window.open('/api/v1/result/download?filepath='+filepath,'_self','');
     }