关于mysql存取图片的三种方式(含源码示例)

您所在的位置:网站首页 用ajax怎么把数据存入数据库 关于mysql存取图片的三种方式(含源码示例)

关于mysql存取图片的三种方式(含源码示例)

2024-07-09 07:57| 来源: 网络整理| 查看: 265

最近在做小程序的后台,要求将小程序用户以upload方法上传的图片保存到mysql数据库中。 然后机缘巧合三种方式都试了,所以专门整理出来分享给大家。可能有的地方说的不太对,欢迎大家帮纠正。

================================================================================

Method1:采用BLOB数据格式存图片。

其实这种方式很不合理,数据库大小会激增会导致简单的查询都及其缓慢。

Method2:采用文本格式存储图片。

虽然也不怎么合理,因为关系型数据库本身就不太适合存巨长的大数据量的东西。 但是由于只涉及到base64加密和解码,且可以都写入后台部分,减轻前端负担。

Method3:将图片单独存放在某个服务器上,数据库只存放他们的url地址。

最高效也是最常用的方法。 后面有展示两种示例。

================================================================================

详细代码示例

================================================================================

Method1详细代码示例:

由于目前做的这个项目,同学A之前一直使用的这种方式将文件中的图片读取到数据库表,所以我只写了对BloB类型图片的取数据部分的代码。且过程较繁琐,可用性不强,就不贴了。

这个代码是A给我发的,实在太久了,她也忘了出处了。有人知道请艾特我一下,我标上链接。

package org.springboot.wechatcity.utill; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * 存入和读取Blob类型的JDBC数据 */ public class BlobUtill { public void getBlob() {//读取Blob数据 Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = JDBCTools.getConnection(); String sql = "SELECT id,name,age,picture FROM animal WHERE id=5"; ps = con.prepareStatement(sql); rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); Blob picture = rs.getBlob(4);//得到Blob对象 //开始读入文件 InputStream in = picture.getBinaryStream(); OutputStream out = new FileOutputStream("cat.png"); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } } catch (Exception e) { e.printStackTrace(); } } public void insertBlob() {//插入Blob Connection con = null; PreparedStatement ps = null; try { con = JDBCTools.getConnection(); String sql = "INSERT INTO animal(name,age,picture) VALUES(?,?,?)"; ps = con.prepareStatement(sql); ps.setString(1, "TheCat"); ps.setInt(2, 8); InputStream in = new FileInputStream("J:/test1/TomCat.png");//生成被插入文件的节点流 //设置Blob ps.setBlob(3, in); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.release(con, ps); } } } package org.springboot.wechatcity.utill; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * JDBC工具类 用来建立连接和释放连接 */ public class JDBCTools { public static Connection getConnection() throws Exception {//连接数据库 String driverClass = "com.mysql.cj.jdbc.Driver"; String url = "jdbc:mysql://IP号:端口号/hmCity?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; String user = ""; String password = ""; Properties properties = new Properties(); InputStream in = Review.class.getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(in); driverClass = properties.getProperty("driver"); url = properties.getProperty("jdbcurl"); user = properties.getProperty("user"); password = properties.getProperty("password"); Class.forName(driverClass); return DriverManager.getConnection(url, user, password); } public static void release(Connection con, Statement state) {//关闭数据库连接 if (state != null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void release(ResultSet rs, Connection con, Statement state) {//关闭数据库连接 if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (state != null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

================================================================================

Method2 详细代码示例:包括存和取的代码 示例:前端以表单形式提交数据信息和图片,后台以MultipartFile类型接收图片,并对图片进行BASE64编码,存储在mysql数据库中。

1.BASE64存图片。 note:建议图片处理部分单独写在service层,比较符合分层规则。

//头部信息 import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Encoder; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * TODO 将用户上传的信息存入数据库中 * 图片以MultipartFile格式上传 * @return */ @CrossOrigin(origins = {"*", "3600"}) //跨域注解,所有域名都可访问,且cookie的有效期为3600秒 @RequestMapping(value = "/pushMessageParam", method = RequestMethod.POST) public int pushMessageBody(@RequestParam String id, MultipartFile file1, MultipartFile file2, MultipartFile file3) throws IOException{//若参数为map或json格式,必须写@RequestBody List files =new ArrayList();//保存用户上传的所有图片,最多三张。 files.add(file1); files.add(file2); files.add(file3); //****给上传的所有jpg、jpeg格式的图片添加头部header(这样取得时候不用解码,直接拿值就行),并进行转码。**** BASE64Encoder base64Encoder = new BASE64Encoder();//BASE64de 解码工具 try { List base64EncoderImgs = new ArrayList();//存放转码后的图片 String header = "";//为转码后的图片添加头部信息 for (int i = 0; i 0就表示in里面还有数据 while ((len = in.read(buffer)) > 0) { //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中 out.write(buffer, 0, len); } //关闭输入流 in.close(); //关闭输出流 out.close(); //删除处理文件上传时生成的临时文件 item.delete(); System.out.println("文件上传服务器成功!"); } } //上传所有文件名 System.out.println("图片名正在上传...请稍等"); //******非spring生命周期用注解需要用到SpringContextUtil工具类***** SubMessageService subMessageService = SpringContextUtil.getBean("sub", SubMessageService.class); GetInfoId id = new GetInfoId();//为了获取ID,专门写的类 int ID = id.getID(); if (names.size() != 0) {//上传了图片 try { subMessageService.uploadAllPictureNames(new PicturesNames(ID, names.get(0), null, null));//根据Id更新所有图片 System.out.println("消息ID为:" + ID); System.out.println("图片名已上传数据库成功~"); }catch (Exception e){ e.printStackTrace(); } } else { System.out.println("未上传图片"); } } catch (Exception e) { System.out.println("文件上传失败!"); e.printStackTrace(); } resultMap.put("code", 0); resultMap.put("msg", "图片上传成功"); return resultMap; }

结果: 在这里插入图片描述 在这里插入图片描述

关于本示例,如果还有困惑或者有兴趣可以戳我另一篇文章。---->>>>小程序后台同时接收前端上传的数据信息和图片的示例


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3