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

目录

1、前言:

2、数据库搭建 :

建表语句:

 3、后端实现,将图片存储进数据库:

思想:

 找到图片位置(如下图操作)

 图片转为Fileinputstream流的工具类(可直接copy)

存储数据库 

 mapper层:

 service层:

 control层:

 4、后端实现,从数据库取出图片给前端(可直接看这个,这个给的是所有代码)

dao层:

mapper层:

service层:

control层:

前端拿到效果: 

5、前端拿到后端传递的json信息渲染到网页

解释 :

如何实现渲染在网页:

尾言 


1、前言:

     我们使用数据库经常传递字符串、数字,但是很少在数据库存储图片、Word文件,我也去csdn找了找其他人的文章,只能说这类型的少的可怜,不是收费,就是讲的乱七八糟。既然如此,那么我将为需要这方面知识点的朋友写下这篇文章。本篇文章我们从以下几个方面:

  • 1、数据库搭建
  • 2、后端实现,将图片存储进数据库
  • 3、后端实现,从数据库取出图片给前端
  • 4、前端拿到后端传递的json信息渲染到网页

废话不多说,直接开始!

2、数据库搭建 :

本次数据库我们选择比较经典的Mysql(只是因为我只会这个),mysql提供一个字段类型叫做

blob,对于这个字段类型,我就不过多详细叙述,csdn博客上有,各位可以去看看。

建表语句:

create table test2(
    id int auto_increment primary key ,
    name varchar(100) comment '名称',
    photo blob comment '照片'
)

 3、后端实现,将图片存储进数据库:

思想:

 思想:实际上我们可以通过字节流的形式,将图片转成二进制,然后将其保存在数据库里面。我们按照以下步骤:

1、找到图片位置

2、图片转为Fileinputstream流

3、存储数据库

 找到图片位置(如下图操作)

 图片转为Fileinputstream流的工具类(可直接copy)

package com.example.jishedemo2.img;

import java.io.*;

public class imgeuntil {
    /**
     * @author Administrator
     *
     */


        // 读取本地图片获取输入流
        public static FileInputStream readImage(String path) throws IOException {
            return new FileInputStream(new File(path));
        }

        // 读取表中图片获取输出流
        public static void readBin2Image(InputStream in, String targetPath) {
            File file = new File(targetPath);
            String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
            if (!file.exists()) {
                new File(path).mkdir();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != fos) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

存储数据库 

 mapper层:

package com.example.jishedemo2.img;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

@Mapper
public interface imagemapper {

 @Insert("insert into test2 values(null,#{name},#{photo})")
 void inser(String name,  FileInputStream photo);

}

 service层:

package com.example.jishedemo2.img;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.util.List;

@Service
public class imageservice implements imge{

    @Autowired
    private imagemapper imagemapper;

    @Override
    public void inser(String name, FileInputStream file) {
        imagemapper.inser(name,file);
    }

}

 control层:

package com.example.jishedemo2.img;

import com.example.jishedemo2.dao.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.List;

@RestController
public class imgedemo {
    @Autowired
    private imageservice imageservice;

    // 将图片插入数据库
    @PostMapping("test3")
    public  void readImage2DB() throws IOException {
        String path = "D:\\wsstext.png";
        try {
            FileInputStream in = null;
            in = imgeuntil.readImage(path);
            imageservice.inser("测试",in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   
}

没什么好说的,如果你不会javaweb,这边建议先去把javaweb学了。

 4、后端实现,从数据库取出图片给前端(可直接看这个,这个给的是所有代码)

这一步,多了一点,我们需要写一个类与数据库的表字段统一(dao层)

dao层:

package com.example.jishedemo2.img;

import java.io.FileInputStream;
import java.io.InputStream;

public class photo {
    int id;
    String name;
    byte[] photo;

    public photo() {
    }

    public photo(int id, String name, byte[] photo) {
        this.id = id;
        this.name = name;
        this.photo = photo;
    }

    /**
     * 获取
     * @return id
     */
    public int getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return photo
     */
    public byte[] getPhoto() {
        return photo;
    }

    /**
     * 设置
     * @param photo
     */
    public void setPhoto(byte[] photo) {
        this.photo = photo;
    }

    public String toString() {
        return "photo{id = " + id + ", name = " + name + ", photo = " + photo + "}";
    }
}

mapper层:

package com.example.jishedemo2.img;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

@Mapper
public interface imagemapper {

 @Insert("insert into test2 values(null,#{name},#{photo})")
 void inser(String name,  FileInputStream photo);

 @Select("select * from test2")
 List<photo> select();


}

service层:

package com.example.jishedemo2.img;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.util.List;

@Service
public class imageservice implements imge{

    @Autowired
    private imagemapper imagemapper;

    @Override
    public void inser(String name, FileInputStream file) {
        imagemapper.inser(name,file);
    }

    @Override
    public List<photo> select() {
        return imagemapper.select();
    }
}

control层:

package com.example.jishedemo2.img;

import com.example.jishedemo2.dao.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.List;

@RestController
public class imgedemo {
    @Autowired
    private imageservice imageservice;

    // 将图片插入数据库
    @PostMapping("test3")
    public  void readImage2DB() throws IOException {
        String path = "D:\\wsstext.png";
        PreparedStatement ps = null;
        try {
            FileInputStream in = null;
            in = imgeuntil.readImage(path);
            imageservice.inser("测试",in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //传数据
    @PostMapping("test4")
    public Result select(){

        List<photo> photos = imageservice.select();

        return Result.success(photos);
    }


}

前端拿到效果: 

5、前端拿到后端传递的json信息渲染到网页

 对于新手前端拿到photo,可能会很蒙蔽不知道这个是什么,我这里简要说一下:

解释 :

这段文本是一个HTML (HyperText Markup Language) 编码的字符串,它嵌入了一个Base64编码的图像数据(以data:image/png;base64,开头的部分,但在这个示例中被截断了),并包含了一些CSS (Cascading Style Sheets) 样式和JavaScript(虽然直接看起来并不包含JavaScript代码,但可能是在某处被引用或嵌入的)。

具体来说,这个字符串包含以下几个部分:

  1. Base64编码的图像数据:这部分以data:image/png;base64,开头,后跟一长串字符,这些字符是图像的二进制数据经过Base64编码后的结果。

  2. CSS样式:字符串中包含了一些CSS样式,如i标签的样式定义(i { ... }),这些样式可能用于控制HTML文档中元素的显示方式。但在这个示例中,CSS样式是直接嵌入在HTML中的,并且由于格式和上下文的原因,可能不完整或难以直接应用。

  3. HTML结构:字符串中包含了HTML的基本结构,如<div><span>等标签,以及自定义的类或ID属性(如class="..."id="..."),这些用于在CSS中引用并应用样式。

  4. JavaScript的引用或嵌入:虽然直接在这个字符串中没有看到JavaScript代码,但通常HTML页面会包含JavaScript代码或引用外部JavaScript文件来控制页面的行为。这个字符串可能只是HTML页面的一部分,而JavaScript代码可能位于其他位置。

  5. 特殊字符和注释:字符串中还包含了一些特殊字符(如//开头的注释)和格式化字符(如换行符\n),这些在HTML和CSS中用于提高代码的可读性和可维护性。

综上所述,这段文本是一个HTML编码的字符串,它结合了Base64编码的图像数据、CSS样式和HTML结构,可能还隐式地引用了JavaScript代码。这种格式常用于在网页中嵌入图像、样式和脚本,以实现丰富的视觉效果和交互功能。

如何实现渲染在网页:

在前端网页中嵌入使用Base64编码的图像字符串,可以直接将这个字符串作为<img>标签的src属性的值。由于Base64编码的图像数据被封装在data: URL中,浏览器可以直接解析这个URL并将其作为图像内容显示在页面上,而无需从外部服务器加载图像。

以下是一个该字符串在前端网页中嵌入图像的示例:

<template>
   <div>  
    <img v-if="imageUrl" :src="imageUrl" alt="Image from backend" />  
  </div>  
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      imageUrl: null
    }
  },
  mounted(){
    
    axios.post("http://localhost:8080/test4").then((e) => {
      this.imageUrl= "data:image/png;base64," + e.data.data[0].photo;
    })
  
}

尾言 

 🏆🏆🏆在本文中,我们深入探讨了如何使用Java实现数据库中的图片上传功能,并详细展示了如何将存储于数据库中的图片数据有效地传递到前端进行渲染。通过整合Spring Boot框架的便利性与数据库管理系统的强大功能,我们构建了一个高效、安全的图片管理系统。不仅实现了图片的上传与存储,还通过接口设计,使得前端能够灵活请求并展示这些图片资源。希望本教程能够为您的项目开发提供有力的技术支持与灵感启发。随着技术的不断进步,未来我们还将继续探索更多关于图像处理与传输的优化方案,以满足日益增长的业务需求。感谢您的阅读,期待与您一同在技术的道路上不断前行!🏆🏆🏆

 

  • 35
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 23
    评论
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值