【问题标题】:Download image in spark java在 spark java 中下载图像
【发布时间】:2016-05-24 05:07:38
【问题描述】:

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

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

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

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

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

当用户点击超链接时,我会调用带有文件路径的函数,但不明白如何发送图像作为响应。

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

我经历了上一个类似的问题,添加尝试为我的场景复制但没有成功

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

How download file using java spark?

编辑: 我确实按照答案中提供的链接强制下载图像,但使用 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 类的示例?

【问题讨论】:

标签: java spark-java


【解决方案1】:

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

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;


   });

角度代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多