springboot保存包含图片的实体对象到数据库并展示到前端页面 具体代码
时间: 2024-02-01 18:16:34 浏览: 95
首先,我们需要定义一个实体类,其中包含保存图片的字段。例如:
```java
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Lob
private byte[] image;
// 省略getter和setter方法
}
```
在这个实体类中,我们使用了`@Lob`注解来指定该字段需要保存大对象。接下来,我们需要编写一个Controller类来处理上传图片和展示图片的请求。
```java
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/product/{id}")
public ResponseEntity<byte[]> getProductImage(@PathVariable Long id) {
Product product = productService.getProductById(id);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<>(product.getImage(), headers, HttpStatus.OK);
}
@PostMapping("/product")
public String saveProduct(@RequestParam("name") String name,
@RequestParam("image") MultipartFile file) throws IOException {
Product product = new Product();
product.setName(name);
product.setImage(file.getBytes());
productService.saveProduct(product);
return "redirect:/";
}
}
```
在这个Controller类中,我们定义了两个方法:`getProductImage`和`saveProduct`。`getProductImage`方法用于根据产品ID获取对应的图片,`saveProduct`方法用于保存新的产品信息到数据库中。
在`saveProduct`方法中,我们使用`@RequestParam`注解来获取前端页面传递过来的产品名称和图片文件。然后,我们创建一个新的`Product`对象,并将产品名称和图片数据设置到该对象中。最后,我们调用`ProductService`的`saveProduct`方法来保存该对象到数据库中。
在`getProductImage`方法中,我们首先根据产品ID从数据库中获取对应的`Product`对象。然后,我们使用`HttpHeaders`对象来设置返回结果的`Content-Type`为`image/jpeg`,表示返回的是JPEG格式的图片数据。最后,我们使用`ResponseEntity`对象来返回图片数据。
最后,我们需要在前端页面中展示图片。例如:
```html
<img src="/product/1" alt="product image">
```
在这个例子中,我们使用`<img>`标签来显示产品图片。其中,`src`属性的值为`/product/1`,表示需要根据产品ID为1获取对应的图片。
阅读全文
相关推荐














