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

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

目录

  1. 项目结构
  2. 数据库表设计
  3. 实现图片上传功能
  4. 实现图片读取和展示
  5. 前端渲染图片
  6. 完整代码展示
  7. 总结

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 从数据库读取图片并在前端渲染显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只蜗牛儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值