【问题标题】:Java + Spring Boot : Downloading image and pass it to a requestJava + Spring Boot:下载图像并将其传递给请求
【发布时间】:2015-06-29 19:57:57
【问题描述】:

我有一个应该像代理一样工作的 Spring Boot 应用程序。

它应该处理像“http://imageservice/picture/123456”这样的请求

然后应用程序应该向“http://internal-picture-db/123456.jpg”生成一个新请求,它应该下载它背后的图片(123456.jpg),然后将它传递给响应并提供它。

应该是……

@RequestMapping("/picture/{id}")
public String getArticleImage(@PathVariable String id, HttpServletResponse response) {

    logger.info("Requested picture >> " + id + " <<");

    // 1. download img from http://internal-picture-db/id.jpg ... 

    // 2. send img to response... ?!

    response.???

}

我希望我的意思很清楚......

所以我的问题是:最好的方法是什么?

而且仅仅为了提供信息,不可能只发送重定向,因为该系统在互联网上不可用。

【问题讨论】:

    标签: java image servlets download spring-boot


    【解决方案1】:

    我会使用响应正文来返回图像而不是视图,例如:

    @RequestMapping("/picture/{id}")
    @ResponseBody
    public HttpEntity<byte[]> getArticleImage(@PathVariable String id) {
    
        logger.info("Requested picture >> " + id + " <<");
    
        // 1. download img from http://internal-picture-db/id.jpg ... 
        byte[] image = ...
    
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(image.length);
    
        return new HttpEntity<byte[]>(image, headers);
    }
    

    您有一个帖子可以帮助您从其他网址下载图片: how to download image from any web page in java

    【讨论】:

    • 很好的解决方案。为我工作。谢谢
    • 有效,但仔细一看,问题是该方法被调用了两次。只是因为 HttpEntity。如果我将返回类型更改为字符串,并且只返回一个随机字符串并下载图像,它只调用一次。所以现在这个方法中的代码被执行了两次。有什么想法或解决方法吗?
    • 如果您返回一个字符串并使用 Base64.encodeBase64URLSafeString(byte[] binaryData) 将图像编码为 base64 会发生什么?
    • 它只显示字符串,因为没有指定内容类型。我不确定如何处理它,因为我将下载和提供的图像并不总是 jpg ,也可能是 gif。我需要将内容类型设置为动态。
    • 我试过@RequestMapping(value = "/picture2/{id}", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif") public @ResponseBody byte[] getArticleImage2(@PathVariable String id) {,它有效但也被执行了两次......?!看来下载的代码让这个执行两次......?!
    【解决方案2】:
    @RequestMapping("/picture/{id}")
    public ResponseEntity<byte[]> getArticleImage(@PathVariable String id) {
    
        logger.info("Requested picture >> " + id + " <<");
    
        // 1. download img from http://internal-picture-db/id.jpg ... 
        byte[] image = ...
    
        return new ResponseEntity<byte[]>(image, HttpStatus.OK);
    }
    

    并在post中查看下载图片的代码。

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多