简体   繁体   English

如何使用 Spring Boot 返回图像

[英]How do I return an image using Spring boot

I am new to Spring boot.我是 Spring Boot 的新手。 I am designing a system using Spring boot, it's a Restful API.我正在使用 Spring boot 设计一个系统,它是一个 Restful API。 I want to display images that the user has uploaded.我想显示用户上传的图片。 I am storing the files in a subfolder "fotos/x" inside resources.我将文件存储在资源内的子文件夹“fotos/x”中。 I instinctively tried to access it by typing我本能地尝试通过键入来访问它

  http://localhost:8080/fotos/76/miniaturas/casa-venda-2-dormitorios-franca-sao-paulo_1.jpg

Holping that Tomcat would serve the image for me but it didn't.希望 Tomcat 会为我提供图像,但事实并非如此。

So I went on and tried to build an endpoint, I've encountered an snippet所以我继续尝试构建一个端点,我遇到了一个片段

       @GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {

    InputStream in = null;
    try{
    in = getClass()
      .getResourceAsStream("/fotos/76/miniaturas/casa-venda-2-dormitorios-franca-sao-paulo_1.jpg");
    }catch(Exception ex){

        System.out.println(ex.getMessage());
    }
    return IOUtils.toByteArray(in);  //toByteArray doesn't exist.
}


}

I found some code that helped me.我找到了一些对我有帮助的代码。

@GetMapping(value = "/imagens/{dir}/{img}", produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImage(@PathVariable String dir, @PathVariable String img) throws IOException {


     byte[] bytes = Files.readAllBytes(Paths.get("/var/www/back_imoveis/back_imoveis/imoveis/src/main/resources/public/fotos/" + dir + "/miniaturas/" + img));

     return bytes;


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Hibernate 和 Spring-boot 从 JPA 查询返回 SUM? - How do I Return SUM from JPA Query Using Hibernate and Spring-boot? 如何使用 Spring Boot 返回成功消息? - How can I return a successful message using Spring Boot? 如何在电子邮件中附加图像? 我正在使用 AWS SES 服务使用 JAVA 发送电子邮件 - Spring Boot - How do i attach image in email? I am using AWS SES Service to send email using JAVA - Spring Boot 如何使用 spring 引导在 Dto 中上传文件 - How do I upload a file in a Dto using spring boot 如何在 Spring 引导中使用 restTemplate 检索资源 object? - How do I retrieve Resource object using restTemplate in Spring Boot? 我如何使 spring boot 嵌入式 tomcat 为基本 url 返回 200 OK? - how do I make spring boot embedded tomcat to return 200 OK for base url? 如何使用Spring Boot使用Postgresql将Spring应用程序部署到Heroku? - How to do I deploy a Spring app using Postgresql to Heroku using Spring Boot? 如何在Spring Boot控制器中返回图像并像文件系统一样提供服务 - How to return an image in Spring Boot controller and serve like a file system 如何使用 Spring Boot 指定 BeanNamingStrategy? - How do I specify a BeanNamingStrategy with Spring Boot? 我如何在 Spring Boot 中编写连接 - How do I Write joins in spring boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM