Spring Boot中无法通过GET方法获取图像?

问题描述 投票:0回答:1

这是我的实体类

@ToString
@Data
@Entity
public class Products {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private BigDecimal price;
    private String description;
    @Lob
    @Column(columnDefinition = "LONGBLOB")
    private byte[] image;
}

这是我的控制器类,我将产品信息发布到 MySQL 数据库,其中包括名称、价格、描述和产品图片

@PostMappig("/product")
public Products uploadProducts(@RequestParam("name") String name, @RequestParam("price") BigDecimal price,
        @RequestParam("description") String description, @RequestParam("image") MultipartFile image,
        @RequestParam("categorys") Categorys thecategory) throws IOException {

    byte[] imageData;

    imageData = image.getBytes();

    Products products = new Products();

    products.setName(name);
    products.setPrice(price);
    products.setDescription(description);
    products.setCategorys(thecategory);
    products.setImage(image);

    return productRepository.save(products);

}
java mysql spring hibernate jpa
1个回答
0
投票

我想使用JAVA spring JPA通过GET方法获取带有产品图片的产品信息?

您可以为您的实体类创建DTO类:

@Data
public class ProductDTO {
    private int id;
    private String name;
    private BigDecimal price;
    private String description;
    private byte[] image;
}

然后在 RestController 中创建 HTTP GET RestApi 方法:

..
...
....
@GetMapping("/product/{id}")
public ResponseEntity<ProductDTO> getProduct(@PathVariable int id) {
    Optional<Products> productOptional = productRepository.findById(id);
    
    if (productOptional.isPresent()) {
        Products product = productOptional.get();
        
        ProductDTO productDTO = new ProductDTO();
        productDTO.setId(product.getId());
        productDTO.setName(product.getName());
        productDTO.setPrice(product.getPrice());
        productDTO.setDescription(product.getDescription());
        productDTO.setImage(product.getImage());
        
        return ResponseEntity
                  .ok(productDTO);
    } else {
        return ResponseEntity
                  .notFound()
                  .build();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.