欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實(shí)現(xiàn)數(shù)據(jù)庫圖片上傳與存儲(chǔ)功能

 更新時(shí)間:2025年03月18日 09:25:13   作者:一只蝸牛兒  
在現(xiàn)代的Web開發(fā)中,上傳圖片并將其存儲(chǔ)在數(shù)據(jù)庫中是常見的需求之一,本文將介紹如何通過Java實(shí)現(xiàn)圖片上傳,存儲(chǔ)到數(shù)據(jù)庫的完整過程,希望對(duì)大家有所幫助

在現(xiàn)代的Web開發(fā)中,上傳圖片并將其存儲(chǔ)在數(shù)據(jù)庫中是常見的需求之一。本文將介紹如何通過Java實(shí)現(xiàn)圖片上傳、存儲(chǔ)到數(shù)據(jù)庫、從數(shù)據(jù)庫讀取并傳遞到前端進(jìn)行渲染的完整過程。

1. 項(xiàng)目結(jié)構(gòu)

在這次實(shí)現(xiàn)中,我們使用 Spring Boot 來處理后臺(tái)邏輯,前端使用 HTML 進(jìn)行渲染。項(xiàng)目的基本結(jié)構(gòu)如下:

├── 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. 數(shù)據(jù)庫表設(shè)計(jì)

我們需要在數(shù)據(jù)庫中存儲(chǔ)圖片的元數(shù)據(jù)信息以及圖片的二進(jìn)制數(shù)據(jù),因此數(shù)據(jù)庫表的設(shè)計(jì)如下:

數(shù)據(jù)庫表結(jié)構(gòu)(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: 主鍵,唯一標(biāo)識(shí)每張圖片。

name: 圖片的名稱。

type: 圖片的類型(如 image/jpeg, image/png 等)。

image_data: 用于存儲(chǔ)圖片的二進(jìn)制數(shù)據(jù)。

3. 實(shí)現(xiàn)圖片上傳功能

3.1 文件上傳控制器

Spring Boot 中通過 @RestController 來實(shí)現(xiàn)上傳文件的接口。在控制器中,我們處理上傳的圖片,并調(diào)用服務(wù)將圖片存儲(chǔ)到數(shù)據(jù)庫。

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 圖片上傳服務(wù)

服務(wù)層負(fù)責(zé)處理文件存儲(chǔ)的邏輯,包括將文件元信息和二進(jìn)制數(shù)據(jù)保存到數(shù)據(jù)庫。

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. 實(shí)現(xiàn)圖片讀取和展示

ImageModel.java

這是用來映射數(shù)據(jù)庫表的實(shí)體類,其中包括圖片的元數(shù)據(jù)信息和二進(jìn)制數(shù)據(jù)。

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 操作數(shù)據(jù)庫。

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. 前端渲染圖片

為了從后端獲取圖片并渲染在網(wǎng)頁上,我們可以通過 HTML 和 JavaScript 實(shí)現(xiàn)。

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>

這個(gè)頁面提供了一個(gè)圖片上傳表單,用戶可以上傳圖片到服務(wù)器。同時(shí),通過 JS 調(diào)用 API 獲取圖片并在頁面上進(jìn)行渲染。

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. 總結(jié)

通過本文的詳細(xì)步驟,您可以學(xué)習(xí)如何使用 Java 實(shí)現(xiàn)圖片的上傳、存儲(chǔ)到數(shù)據(jù)庫,并通過 API 從數(shù)據(jù)庫讀取圖片并在前端渲染顯示。

以上就是Java實(shí)現(xiàn)數(shù)據(jù)庫圖片上傳與存儲(chǔ)功能的詳細(xì)內(nèi)容,更多關(guān)于Java數(shù)據(jù)庫圖片上傳的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 一篇文章帶你搞定JAVA Maven

    一篇文章帶你搞定JAVA Maven

    Maven是每個(gè)Java程序都會(huì)遇到的包管理工具,今天整理一下Maven的相關(guān)知識(shí),從青銅到王者,一文全了解,我們開始吧,希望對(duì)你有所幫助
    2021-07-07
  • Netty中序列化的作用及自定義協(xié)議詳解

    Netty中序列化的作用及自定義協(xié)議詳解

    這篇文章主要介紹了Netty中序列化的作用及自定義協(xié)議詳解,Netty自身就支持很多種協(xié)議比如Http、Websocket等等,但如果用來作為自己的RPC框架通常會(huì)自定義協(xié)議,所以這也是本文的重點(diǎn),需要的朋友可以參考下
    2023-12-12
  • 詳解RSA加密算法的原理與Java實(shí)現(xiàn)

    詳解RSA加密算法的原理與Java實(shí)現(xiàn)

    這篇文章主要和大家分享非對(duì)稱加密中的一種算法,那就是 RSA 加密算法。本文介紹了RSA算法的原理與Java實(shí)現(xiàn),感興趣的小伙伴可以嘗試一下
    2022-10-10
  • SpringBoot框架底層原理解析

    SpringBoot框架底層原理解析

    這篇文章主要介紹了SpringBoot底層原理,包括配置優(yōu)先級(jí)的配置方式給大家講解的非常詳細(xì),需要的朋友可以參考下
    2024-03-03
  • SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式

    SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式

    在Web應(yīng)用程序開發(fā)中,統(tǒng)一數(shù)據(jù)返回格式對(duì)于前后端分離項(xiàng)目尤為重要,本文就來介紹一下SpringBoot統(tǒng)一數(shù)據(jù)返回的幾種方式,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-07-07
  • springboot如何獲取相對(duì)路徑文件夾下靜態(tài)資源的方法

    springboot如何獲取相對(duì)路徑文件夾下靜態(tài)資源的方法

    這篇文章主要介紹了springboot如何獲取相對(duì)路徑文件夾下靜態(tài)資源的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-05-05
  • Java用freemarker導(dǎo)出word實(shí)用示例

    Java用freemarker導(dǎo)出word實(shí)用示例

    本篇文章主要介紹了Java用freemarker導(dǎo)出word實(shí)用示例,使用freemarker的模板來實(shí)現(xiàn)功能,有需要的可以了解一下。
    2016-11-11
  • Java中if語句return用法和有無括號(hào)的區(qū)別

    Java中if語句return用法和有無括號(hào)的區(qū)別

    本文主要介紹了Java中if語句return用法和有無括號(hào)的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-12-12
  • mybatis where 標(biāo)簽使用

    mybatis where 標(biāo)簽使用

    where標(biāo)記的作用類似于動(dòng)態(tài)sql中的set標(biāo)記,本文主要介紹了mybatis where 標(biāo)簽使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Spring?Security?OAuth?Client配置加載源碼解析

    Spring?Security?OAuth?Client配置加載源碼解析

    這篇文章主要為大家介紹了Spring?Security?OAuth?Client配置加載源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07

最新評(píng)論