【问题标题】:how to get the path of upload images in Sparkjava framework?Sparkjava框架中如何获取上传图片的路径?
【发布时间】:2016-08-16 06:29:45
【问题描述】:

在我的项目中,我通过upload method中的方法上传图片。 项目目录是:

Project
   |---src/main/java
   |---src/main/resources
                   |---static
                          |---css
                               |---default.css
   |---upload
         |---1.jpg
         |---2.jpg

freemarker 渲染的视图页面。在我的showimage.ftl文件中,img标签<img src="...">,如何在src中定义上传的图片路径。

如果把上传图片放在src/main/resources,我可以使用staticFileLocation的方法访问,但是不能上传图片到资源目录。

【问题讨论】:

    标签: java spark-java


    【解决方案1】:

    您需要获取文件流,并发送原始响应。 只需根据您的请求对象修改代码以获得灵活的路径。

    try {
       String path = "upload/1.jpg";
       Path p = Paths.get(path);
    
       InputStream is = new FileInputStream(p.toFile());
    
       res.raw().setContentType(Files.probeContentType(p));
       res.raw().setHeader("Content-Disposition", "inline; filename=" + p.getFileName());
    
       byte[] buffer = new byte[1024];
       int len;
       while ((len = is.read(buffer)) > 0) {
          res.raw().getOutputStream().write(buffer, 0, len);
       }
    
       String result = IOUtils.toString(is);
       is.close();
       return result.trim();
    } catch (Exception e) { // handle the exceptions the way you want
       logger.error("Error while getting resource", e);
       res.status(500);
       return "";
    }
    

    【讨论】:

    • 你的解决方案不是很理想。您不能将流转换为字符串,存储在内存中,只是为了将其发送给客户端。为什么不直接将其流式传输到 Outputstream 以避免内存问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多