有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Spring boot返回映像

我对Spring boot还不熟悉。我正在设计一个使用Spring boot的系统,这是一个Restful API。我想显示用户上传的图像。我将文件存储在参考资料中的子文件夹“fotos/x”中。我本能地试图通过打字来访问它

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

Holping Tomcat会为我服务,但它没有

所以我继续尝试构建一个端点,我遇到了一个片段

       @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.
}


}

共 (1) 个答案

  1. # 1 楼答案

    我找到了一些帮助我的代码

    @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;
    
    
    }