在 spark java 中下载图像

Download image in spark java

我关注了 spark github 页面上的讨论以及堆栈溢出,以了解如何使用 spark 和 apache 文件上传来上传文件。

现在我希望用户可以选择在点击时下载图像。

例如,我上传的文件存储在服务器上的 /tmp/imageName.jpg 中。

在客户端,我想在用户单击 hyperlink 时为用户提供下载文件的选项。

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

当用户点击 hyperlink 我会用文件路径调用该函数,但不明白如何发送图像作为响应。

我知道 HTML5 有 download attribute,但这需要将文件保存在服务器上的 public 文件夹中,这是不可能的。

我经历了之前的类似问题添加尝试复制我的场景但没有成功

How download file using java spark?

编辑: 我确实按照答案中提供的 link 强制下载图像,但使用 response.raw() 我无法获得响应

response.type("application/force-download");
        response.header("Content-Transfer-Encoding", "binary");
        response.header("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
        try {
        HttpServletResponse raw = response.raw();
        PrintWriter out = raw.getWriter();
        File f= new File("/tmp/Tulips.jpg");

        InputStream in = new FileInputStream(f);
        BufferedInputStream bin = new BufferedInputStream(in);
        DataInputStream din = new DataInputStream(bin);

        while(din.available() > 0){
            out.print(din.read());
            out.print("\n");
        }

        }
        catch (Exception e1) {
            e1.printStackTrace();
        }
        response.status(200);
        return response.raw();

编辑 2:

我不确定使用 response.body () 与 response.raw().someFunction() 之间有什么区别。在任何一种情况下,我似乎都可以将数据发回作为响应。即使我写了一个简单的 response.body("hello") 它也没有反映在我的回复中。

读取文件的方式与读取图像的方式有区别吗?使用 ImageIO 的示例 class ?

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

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代码

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