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

news/2024/10/11 1:22:17/

目录

1、前言:

2、数据库搭建 :

建表语句:

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

思想:

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

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

存储数据库 

 mapper层:

 service层:

 control层:

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

dao层:

mapper层:

service层:

control层:

前端拿到效果: 

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

解释 :

如何实现渲染在网页:

尾言 


1、前言:

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

废话不多说,直接开始!

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{@Autowiredprivate imagemapper imagemapper;@Overridepublic 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 {@Autowiredprivate 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{@Autowiredprivate imagemapper imagemapper;@Overridepublic void inser(String name, FileInputStream file) {imagemapper.inser(name,file);}@Overridepublic 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 {@Autowiredprivate 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框架的便利性与数据库管理系统的强大功能,我们构建了一个高效、安全的图片管理系统。不仅实现了图片的上传与存储,还通过接口设计,使得前端能够灵活请求并展示这些图片资源。希望本教程能够为您的项目开发提供有力的技术支持与灵感启发。随着技术的不断进步,未来我们还将继续探索更多关于图像处理与传输的优化方案,以满足日益增长的业务需求。感谢您的阅读,期待与您一同在技术的道路上不断前行!🏆🏆🏆

 


http://www.ppmy.cn/news/1503254.html

相关文章

Qt实现简易CAD软件的开发:技术解析与实现

文章目录 简易CAD软件的开发&#xff1a;技术解析与实现引言项目概述程序入口主窗口的实现主窗口类定义&#xff08;mainwindow.h&#xff09;主窗口类实现&#xff08;mainwindow.cpp&#xff09; 自定义绘图视图自定义绘图视图类定义&#xff08;myqgraphicsview.h&#xff0…

【WEB】ctfshow-萌新-web9-15

文章目录 题目介绍&#xff1a;题目分析&#xff1a;payload&#xff1a; 题目介绍&#xff1a; ctfshow-萌新计划-web9-15 <?php # flag in config.php include("config.php"); if(isset($_GET[c])){$c $_GET[c];if(preg_match("/system|exec|highlight…

编程小白如何成为大神?大学新生的最佳入门攻略

&#x1f4e2;博客主页&#xff1a;https://blog.csdn.net/2301_779549673 &#x1f4e2;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01; &#x1f4e2;本文由 JohnKi 原创&#xff0c;首发于 CSDN&#x1f649; &#x1f4e2;未来很长&#…

PostgreSQL入门与进阶学习,体系化的SQL知识,完成终极目标高可用与容灾,性能优化与架构设计,以及安全策略

​专栏内容&#xff1a; postgresql使用入门基础手写数据库toadb并发编程 个人主页&#xff1a;我的主页 管理社区&#xff1a;开源数据库 座右铭&#xff1a;天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物. 文章目录 概述基础篇初级篇进阶篇…

高效办公新选择:2024年福昕PDF同类软件精选

现在大家都开始使用PDF文档格式来进行文件的传输&#xff0c;随着使用率的增加&#xff0c;大家已经不局限于“只读”式的PDF文件了&#xff0c;使用福昕pdf这种PDF编辑软件就可以体验阅读、编辑PDF。 1.福昕PDF编辑器 链接直达>>https://editor.foxitsoftware.cn 这…

基于Python的哔哩哔哩国产动画排行数据分析系统

需要本项目的可以私信博主&#xff0c;提供完整的部署、讲解、文档、代码服务 随着经济社会的快速发展&#xff0c;中国影视产业迎来了蓬勃发展的契机&#xff0c;其中动漫产业发展尤为突出。中国拥有古老而又璀璨的文明&#xff0c;仅仅从中提取一部分就足以催生出大量精彩的…

昇思25天学习打卡营第22天|CycleGAN图像风格迁移互换

相关知识 CycleGAN 循环生成网络&#xff0c;实现了在没有配对示例的情况下将图像从源域X转换到目标域Y的方法&#xff0c;应用于域迁移&#xff0c;也就是图像风格迁移。上章介绍了可以完成图像翻译任务的Pix2Pix&#xff0c;但是Pix2Pix的数据必须是成对的。CycleGAN中只需…

【AWS基础】AWS服务介绍与基本使用

AWS基础&#xff1a;AWS服务介绍与基本使用 目录 引言AWS概述AWS的核心服务 计算服务存储服务数据库服务网络服务管理和监控服务 AWS的基本使用 创建AWS账户使用EC2实例使用S3存储配置RDS数据库设置VPC网络 AWS的优势AWS的应用场景结论 引言 亚马逊网络服务&#xff08;AWS&…