0


Java实现数据库图片上传(包含从数据库拿图片传递前端渲染)

在现代的Web开发中,上传图片并将其存储在数据库中是常见的需求之一。本文将介绍如何通过Java实现图片上传、存储到数据库、从数据库读取并传递到前端进行渲染的完整过程。

目录


1. 项目结构

在这次实现中,我们使用 Spring Boot 来处理后台逻辑,前端使用 HTML 进行渲染。项目的基本结构如下:

  1. ├── src
  2. ├── main
  3. ├── java
  4. └── com
  5. └── example
  6. └── imageupload
  7. ├── controller
  8. └── ImageController.java
  9. ├── service
  10. └── ImageService.java
  11. ├── repository
  12. └── ImageRepository.java
  13. └── model
  14. └── ImageModel.java
  15. └── resources
  16. ├── templates
  17. └── index.html
  18. └── application.properties

2. 数据库表设计

我们需要在数据库中存储图片的元数据信息以及图片的二进制数据,因此数据库表的设计如下:

数据库表结构(

  1. image_table

  1. CREATETABLE image_table (
  2. id BIGINTPRIMARYKEYAUTO_INCREMENT,
  3. name VARCHAR(255)NOTNULL,typeVARCHAR(50)NOTNULL,
  4. image_data LONGBLOBNOTNULL);
  • id: 主键,唯一标识每张图片。
  • name: 图片的名称。
  • type: 图片的类型(如 image/jpeg, image/png 等)。
  • image_data: 用于存储图片的二进制数据。

3. 实现图片上传功能

3.1 文件上传控制器

Spring Boot 中通过

  1. @RestController

来实现上传文件的接口。在控制器中,我们处理上传的图片,并调用服务将图片存储到数据库。

ImageController.java
  1. packagecom.example.imageupload.controller;importcom.example.imageupload.service.ImageService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.http.ResponseEntity;importorg.springframework.web.bind.annotation.*;importorg.springframework.web.multipart.MultipartFile;@RestController@RequestMapping("/api/images")publicclassImageController{@AutowiredprivateImageService imageService;@PostMapping("/upload")publicResponseEntity<String>uploadImage(@RequestParam("file")MultipartFile file){try{
  2. imageService.saveImage(file);returnResponseEntity.ok("Image uploaded successfully.");}catch(Exception e){returnResponseEntity.status(500).body("Image upload failed: "+ e.getMessage());}}@GetMapping("/{id}")publicResponseEntity<byte[]>getImage(@PathVariableLong id){byte[] imageData = imageService.getImage(id);returnResponseEntity.ok(imageData);}}

3.2 图片上传服务

服务层负责处理文件存储的逻辑,包括将文件元信息和二进制数据保存到数据库。

ImageService.java
  1. packagecom.example.imageupload.service;importcom.example.imageupload.model.ImageModel;importcom.example.imageupload.repository.ImageRepository;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.web.multipart.MultipartFile;importjava.io.IOException;@ServicepublicclassImageService{@AutowiredprivateImageRepository imageRepository;publicvoidsaveImage(MultipartFile file)throwsIOException{ImageModel image =newImageModel();
  2. image.setName(file.getOriginalFilename());
  3. image.setType(file.getContentType());
  4. image.setImageData(file.getBytes());
  5. imageRepository.save(image);}publicbyte[]getImage(Long id){ImageModel image = imageRepository.findById(id).orElseThrow(()->newRuntimeException("Image not found."));return image.getImageData();}}

4. 实现图片读取和展示

ImageModel.java

这是用来映射数据库表的实体类,其中包括图片的元数据信息和二进制数据。

  1. packagecom.example.imageupload.model;importjavax.persistence.*;@Entity@Table(name ="image_table")publicclassImageModel{@Id@GeneratedValue(strategy =GenerationType.IDENTITY)privateLong id;privateString name;privateString type;@Lobprivatebyte[] imageData;// Getters and Setters}

ImageRepository.java

使用 Spring Data JPA 操作数据库。

  1. packagecom.example.imageupload.repository;importcom.example.imageupload.model.ImageModel;importorg.springframework.data.jpa.repository.JpaRepository;importorg.springframework.stereotype.Repository;@RepositorypublicinterfaceImageRepositoryextendsJpaRepository<ImageModel,Long>{}

5. 前端渲染图片

为了从后端获取图片并渲染在网页上,我们可以通过 HTML 和 JavaScript 实现。

index.html

  1. <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Image Upload</title></head><body><h1>Upload Image</h1><formaction="/api/images/upload"method="post"enctype="multipart/form-data"><inputtype="file"name="file"accept="image/*"required><buttontype="submit">Upload</button></form><h2>Image Preview</h2><imgid="preview"src=""alt="No image"width="300px"><script>functionfetchImage(){const imageId =1;// 替换为你需要的图片IDfetch(`/api/images/${imageId}`).then(response=> response.blob()).then(blob=>{const url =URL.createObjectURL(blob);
  2. document.getElementById('preview').src = url;});}
  3. window.onload = fetchImage;</script></body></html>

这个页面提供了一个图片上传表单,用户可以上传图片到服务器。同时,通过 JS 调用 API 获取图片并在页面上进行渲染。


6. 完整代码展示

application.properties

  1. spring.datasource.url=jdbc:mysql://localhost:3306/mydb
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.jpa.hibernate.ddl-auto=update

7. 总结

通过本文的详细步骤,您可以学习如何使用 Java 实现图片的上传、存储到数据库,并通过 API 从数据库读取图片并在前端渲染显示。

标签: java 数据库 前端

本文转载自: https://blog.csdn.net/qq_42978535/article/details/142670393
版权归原作者 一只蜗牛儿 所有, 如有侵权,请联系我们删除。

“Java实现数据库图片上传(包含从数据库拿图片传递前端渲染)”的评论:

还没有评论