In modern web development, uploading images and storing them in databases is one of the common needs. This article will introduce the complete process of how to upload, store it to the database, read it from the database and pass it to the front-end for rendering through Java.
1. Project structure
In this implementation, we use Spring Boot to handle background logic, and the front-end uses HTML for rendering. The basic structure of the project is as follows:
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── imageupload
│ │ │ ├── controller
│ │ │ │ └──
│ │ │ ├── service
│ │ │ │ └──
│ │ │ ├── repository
│ │ │ │ └──
│ │ │ └── model
│ │ │ └──
│ └── resources
│ ├── templates
│ │ └──
│ └──
2. Database table design
We need to store the metadata information of the image and the binary data of the image in the database, so the design of the database table is as follows:
Database table structure (image_table)
CREATE TABLE image_table ( id BIGINT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL, type VARCHAR(50) NOT NULL, image_data LONGBLOB NOT NULL );
id: primary key, uniquely identifying each image.
name: The name of the image.
type: The type of image (such as image/jpeg, image/png, etc.).
image_data: Binary data used to store images.
3. Implement the image upload function
3.1 File Upload Controller
The @RestController is used in Spring Boot to implement the interface for uploading files. In the controller, we process the uploaded images and call the service to store the images to the database.
package ; import ; import ; import ; import .*; import ; @RestController @RequestMapping("/api/images") public class ImageController { @Autowired private ImageService imageService; @PostMapping("/upload") public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) { try { (file); return ("Image uploaded successfully."); } catch (Exception e) { return (500).body("Image upload failed: " + ()); } } @GetMapping("/{id}") public ResponseEntity<byte[]> getImage(@PathVariable Long id) { byte[] imageData = (id); return (imageData); } }
3.2 Image upload service
The service layer is responsible for processing the logic of file storage, including saving file meta information and binary data to the database.
package ; import ; import ; import ; import ; import ; import ; @Service public class ImageService { @Autowired private ImageRepository imageRepository; public void saveImage(MultipartFile file) throws IOException { ImageModel image = new ImageModel(); (()); (()); (()); (image); } public byte[] getImage(Long id) { ImageModel image = (id).orElseThrow(() -> new RuntimeException("Image not found.")); return (); } }
4. Realize image reading and display
This is the entity class used to map database tables, including the metadata information and binary data of the image.
package ; import .*; @Entity @Table(name = "image_table") public class ImageModel { @Id @GeneratedValue(strategy = ) private Long id; private String name; private String type; @Lob private byte[] imageData; // Getters and Setters }
Use Spring Data JPA to operate the database.
package ; import ; import ; import ; @Repository public interface ImageRepository extends JpaRepository<ImageModel, Long> { }
5. Front-end rendering picture
In order to get the image from the backend and render it on a web page, we can do it through HTML and JavaScript.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Upload</title> </head> <body> <h1>Upload Image</h1> <form action="/api/images/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" accept="image/*" required> <button type="submit">Upload</button> </form> <h2>Image Preview</h2> <img src="" alt="No image" width="300px"> <script> function fetchImage() { const imageId = 1; // Replace with the image ID you need fetch(`/api/images/${imageId}`) .then(response => ()) .then(blob => { const url = (blob); ('preview').src = url; }); } = fetchImage; </script> </body> </html>
This page provides an image upload form where users can upload images to the server. At the same time, the image is obtained through the JS call API and rendered on the page.
6. Full code display
=jdbc:mysql://localhost:3306/mydb =root =root -auto=update
7. Summary
Through the detailed steps in this article, you can learn how to use Java to upload, store images to the database, and read images from the database through the API and render them on the front-end.
The above is the detailed content of Java implementing database image upload and storage functions. For more information about Java database image upload, please pay attention to my other related articles!