IT评测·应用市场-qidao123.com
标题:
Java实现数据库图片上传(包含从数据库拿图片传递前端渲染)
[打印本页]
作者:
宁睿
时间:
2024-12-14 10:28
标题:
Java实现数据库图片上传(包含从数据库拿图片传递前端渲染)
在当代的Web开发中,上传图片并将其存储在数据库中是常见的需求之一。本文将介绍怎样通过Java实现图片上传、存储到数据库、从数据库读取并传递到前端进行渲染的完整过程。
目录
项目结构
数据库表设计
实现图片上传功能
3.1 文件上传控制器
3.2 图片上传服务
实现图片读取和展示
前端渲染图片
完整代码展示
总结
1. 项目结构
在这次实现中,我们利用 Spring Boot 来处置惩罚背景逻辑,前端利用 HTML 进行渲染。项目标根本结构如下:
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── imageupload
│ │ │ ├── controller
│ │ │ │ └── ImageController.java
│ │ │ ├── service
│ │ │ │ └── ImageService.java
│ │ │ ├── repository
│ │ │ │ └── ImageRepository.java
│ │ │ └── model
│ │ │ └── ImageModel.java
│ └── resources
│ ├── templates
│ │ └── index.html
│ └── application.properties
复制代码
2. 数据库表设计
我们必要在数据库中存储图片的元数据信息以及图片的二进制数据,因此数据库表的设计如下:
数据库表结构(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: 主键,唯一标识每张图片。
name: 图片的名称。
type: 图片的范例(如 image/jpeg, image/png 等)。
image_data: 用于存储图片的二进制数据。
3. 实现图片上传功能
3.1 文件上传控制器
Spring Boot 中通过 @RestController 来实现上传文件的接口。在控制器中,我们处置惩罚上传的图片,并调用服务将图片存储到数据库。
ImageController.java
package com.example.imageupload.controller;
import com.example.imageupload.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api/images")
public class ImageController {
@Autowired
private ImageService imageService;
@PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
try {
imageService.saveImage(file);
return ResponseEntity.ok("Image uploaded successfully.");
} catch (Exception e) {
return ResponseEntity.status(500).body("Image upload failed: " + e.getMessage());
}
}
@GetMapping("/{id}")
public ResponseEntity<byte[]> getImage(@PathVariable Long id) {
byte[] imageData = imageService.getImage(id);
return ResponseEntity.ok(imageData);
}
}
复制代码
3.2 图片上传服务
服务层负责处置惩罚文件存储的逻辑,包罗将文件元信息和二进制数据保存到数据库。
ImageService.java
package com.example.imageupload.service;
import com.example.imageupload.model.ImageModel;
import com.example.imageupload.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
public void saveImage(MultipartFile file) throws IOException {
ImageModel image = new ImageModel();
image.setName(file.getOriginalFilename());
image.setType(file.getContentType());
image.setImageData(file.getBytes());
imageRepository.save(image);
}
public byte[] getImage(Long id) {
ImageModel image = imageRepository.findById(id).orElseThrow(() -> new RuntimeException("Image not found."));
return image.getImageData();
}
}
复制代码
4. 实现图片读取和展示
ImageModel.java
这是用来映射数据库表的实体类,此中包罗图片的元数据信息和二进制数据。
package com.example.imageupload.model;
import javax.persistence.*;
@Entity
@Table(name = "image_table")
public class ImageModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String type;
@Lob
private byte[] imageData;
// Getters and Setters
}
复制代码
ImageRepository.java
利用 Spring Data JPA 操纵数据库。
package com.example.imageupload.repository;
import com.example.imageupload.model.ImageModel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ImageRepository extends JpaRepository<ImageModel, Long> {
}
复制代码
5. 前端渲染图片
为了从后端获取图片并渲染在网页上,我们可以通过 HTML 和 JavaScript 实现。
index.html
<!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 id="preview" src="" alt="No image" width="300px">
<script>
function fetchImage() {
const imageId = 1; // 替换为你需要的图片ID
fetch(`/api/images/${imageId}`)
.then(response => response.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
document.getElementById('preview').src = url;
});
}
window.onload = fetchImage;
</script>
</body>
</html>
复制代码
这个页面提供了一个图片上传表单,用户可以上传图片到服务器。同时,通过 JS 调用 API 获取图片并在页面上进行渲染。
6. 完整代码展示
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
复制代码
7. 总结
通过本文的详细步骤,您可以学习怎样利用 Java 实现图片的上传、存储到数据库,并通过 API 从数据库读取图片并在前端渲染表现。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4