当前位置:   article > 正文

base64存储图片/显示图片_base64图片

base64图片

不知道大家有没有这样一个需求:发布一篇文章,文章内容中可能涉及到图片,那么显示文章时候,如何展示文章如发布一样(包括图片),csdn 的发布文章就是一个很好的例子,虽然我不知道csdn是如何实现的,但我自己的实现方法主要有两种:

1.在富文本编辑器中上传图片,以IO流方式存储到文件服务器,上传成功后,返回图片的http地址(回显)

2.在富文本编辑器中上传图片,将图片以base64方式存储到数据表中

本文章讲的是第二种方式(base64):

demo样例(demo下载):

注:

富文本编辑器:wangEditor2

数据库:SQL Server 

开发环境:jdk1.8.0 、java语言

步骤:

1.首先,创建示例数据表如下图(demo完成后自行上传404图片):

2.制作富文本编辑器UI页面index.jsp

3.富文本编辑器处理上传js:

  1. $(function() {
  2. var path = $("#path").val();
  3. var editor = new wangEditor('div1');
  4. // 自定义菜单
  5. editor.config.menus = [
  6. 'lineheight',
  7. 'undo',
  8. 'bold',
  9. 'italic',
  10. 'underline',
  11. 'strikethrough',
  12. 'fontfamily',
  13. 'fontsize',
  14. 'forecolor',
  15. 'bgcolor',
  16. 'table',
  17. 'img'
  18. ];
  19. /*
  20. * 默认菜单
  21. * [
  22. 'source',
  23. '|',
  24. 'bold',
  25. 'underline',
  26. 'italic',
  27. 'strikethrough',
  28. 'eraser',
  29. 'forecolor',
  30. 'bgcolor',
  31. '|',
  32. 'quote',
  33. 'fontfamily',
  34. 'fontsize',
  35. 'head',
  36. 'unorderlist',
  37. 'orderlist',
  38. 'alignleft',
  39. 'aligncenter',
  40. 'alignright',
  41. '|',
  42. 'link',
  43. 'unlink',
  44. 'table',
  45. 'emotion',
  46. '|',
  47. 'img',
  48. 'video',
  49. 'location',
  50. 'insertcode',
  51. '|',
  52. 'undo',
  53. 'redo',
  54. 'fullscreen'
  55. ];
  56. * */
  57. // 字体
  58. editor.config.familys = [
  59. '宋体','仿宋GB2312','华文仿宋', '黑体', '楷体', '微软雅黑',
  60. 'Arial', 'Verdana', 'Georgia'
  61. ];
  62. // 字号
  63. editor.config.fontsizes = {
  64. // 格式:'value': 'title'
  65. 1: '10',
  66. 2: '10.5',
  67. 3: '11',
  68. 4: '11.5',
  69. 5: '12',
  70. 6: '12.5',
  71. 7: '13',
  72. 8: '13.5',
  73. 9: '14',
  74. 10: '14.5',
  75. 11: '15',
  76. 12: '15.5',
  77. 13: '16'
  78. };
  79. // 上传图片
  80. editor.config.uploadImgUrl = path+"/upload/uploadManager.jsp?method=post";
  81. // 关闭粘贴内容中的样式
  82. //editor.customConfig.pasteFilterStyle = false
  83. // 忽略粘贴内容中的图片
  84. //editor.customConfig.pasteIgnoreImg = true
  85. // 使用 base64 保存图片
  86. //editor.customConfig.uploadImgShowBase64 = true
  87. // 若需传参,请在此配置参数
  88. editor.config.uploadParams = {
  89. /* token1: 'abcde',
  90. token2: '12345'*/
  91. };
  92. editor.config.uploadHeaders = {
  93. // 'Accept' : 'text/x-json'
  94. }
  95. // 配置统一名字,方便后台获取
  96. editor.config.uploadImgFileName = 'myFileName';
  97. // 隐藏网络图片
  98. editor.config.hideLinkImg = true;
  99. // 将图片大小限制为 3M
  100. //editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
  101. // 自定义上传图片事件
  102. editor.config.uploadImgFns.onload = function (resultText, xhr) {
  103. // resultText 服务器端返回的text
  104. // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
  105. var data = JSON.parse(resultText.trim());
  106. //srcList.add(basePath+"/upload/uploadManager.jsp?method=get&FID="+FID);
  107. var FIDs = data.FIDs;
  108. for(var i in FIDs){
  109. var fid = FIDs[i];
  110. var src = path+"/upload/uploadManager.jsp?method=get&FID="+fid;
  111. // 上传图片时,已经将图片的名字存在 editor.uploadImgOriginalName
  112. var originalName = editor.uploadImgOriginalName || '';
  113. // 如果 resultText 是图片的url地址,可以这样插入图片:
  114. editor.command(null, 'insertHtml', '<img src="' + src + '" alt="' + originalName + '" style="max-width:100%;"/>');
  115. // 如果不想要 img 的 max-width 样式,也可以这样插入:
  116. // editor.command(null, 'InsertImage', resultText);
  117. }
  118. };
  119. // 自定义timeout事件
  120. editor.config.uploadImgFns.ontimeout = function (xhr) {
  121. // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
  122. alert('上传超时');
  123. };
  124. // 自定义error事件
  125. editor.config.uploadImgFns.onerror = function (xhr) {
  126. // xhr 是 xmlHttpRequest 对象,IE8、9中不支持
  127. alert('上传错误');
  128. };
  129. // 插入代码时的默认语言
  130. // editor.config.codeDefaultLang = 'html'
  131. // 只粘贴纯文本
  132. // editor.config.pasteText = true;
  133. // 跨域上传
  134. // editor.config.uploadImgUrl = 'http://localhost:8012/upload';
  135. // 第三方上传
  136. // editor.config.customUpload = true;
  137. // 普通菜单配置
  138. // editor.config.menus = [
  139. // 'img',
  140. // 'insertcode',
  141. // 'eraser',
  142. // 'fullscreen'
  143. // ];
  144. // 只排除某几个菜单(兼容IE低版本,不支持ES5的浏览器),支持ES5的浏览器可直接用 [].map 方法
  145. // editor.config.menus = $.map(wangEditor.config.menus, function(item, key) {
  146. // if (item === 'insertcode') {
  147. // return null;
  148. // }
  149. // if (item === 'fullscreen') {
  150. // return null;
  151. // }
  152. // return item;
  153. // });
  154. // onchange 事件
  155. editor.onchange = function () {
  156. // var text = this.$txt.html().replace("a","span").replace("href","h");
  157. //this.$txt.html(text);
  158. console.log(this.$txt.html());
  159. };
  160. // 取消过滤js
  161. // editor.config.jsFilter = false;
  162. // 取消粘贴过来
  163. // editor.config.pasteFilter = false;
  164. // 设置 z-index
  165. // editor.config.zindex = 20000;
  166. // 语言
  167. // editor.config.lang = wangEditor.langs['en'];
  168. // 自定义菜单UI
  169. // editor.UI.menus.bold = {
  170. // normal: '<button style="font-size:20px; margin-top:5px;">B</button>',
  171. // selected: '.selected'
  172. // };
  173. // editor.UI.menus.italic = {
  174. // normal: '<button style="font-size:20px; margin-top:5px;">I</button>',
  175. // selected: '<button style="font-size:20px; margin-top:5px;"><i>I</i></button>'
  176. // };
  177. editor.create();
  178. })

4.后台将图片保存至数据库:

  1. package com.demo.io;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.io.PrintWriter;
  8. import java.sql.Connection;
  9. import java.sql.ResultSet;
  10. import java.sql.Statement;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.UUID;
  14. import javax.servlet.ServletOutputStream;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpServletResponse;
  17. import javax.servlet.http.HttpSession;
  18. import org.apache.commons.fileupload.FileItem;
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  21. import org.apache.jasper.tagplugins.jstl.core.Out;
  22. import org.json.JSONObject;
  23. import com.demo.utils.DBUtils;
  24. import com.google.gson.Gson;
  25. import sun.misc.BASE64Decoder;
  26. import sun.misc.BASE64Encoder;
  27. public class UploadImages {
  28. public static void main(String[] args) {
  29. new Gson();
  30. }
  31. public static List<String> uploadImages(HttpServletRequest request) throws IOException {
  32. Connection conn = null;
  33. String basePath = request.getContextPath();
  34. List<String> FIDs = new ArrayList<String>();
  35. BASE64Encoder encoder = new BASE64Encoder();
  36. /** 上传文件处理内容 **/
  37. DiskFileItemFactory factory = new DiskFileItemFactory();
  38. ServletFileUpload sfu = new ServletFileUpload(factory);
  39. sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
  40. sfu.setSizeMax(10 * 1024 * 1024); // 限制文件大小
  41. try {
  42. conn = DBUtils.getConnection();
  43. if (conn != null) {
  44. StringBuffer sql = new StringBuffer("");
  45. List<FileItem> fileItems = sfu.parseRequest(request); // decode request
  46. for (FileItem fi : fileItems) {
  47. String FID = getUUID();
  48. if(!FID.equals("")) {
  49. String imgName = fi.getName();
  50. String imgByte = encoder.encode(fi.get());
  51. sql.append(" INSERT INTO Base64Images(FID,imageName,imageObj,IsDelete) ");
  52. sql.append(" VALUES ");
  53. sql.append(" ('"+FID+"','"+imgName+"','"+imgByte+"',0) ");
  54. Statement stm = conn.createStatement();
  55. int i = stm.executeUpdate(sql.toString());
  56. stm.close();
  57. if(i > 0) {
  58. FIDs.add(FID);
  59. }
  60. }
  61. }
  62. }
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }finally {
  66. DBUtils.release(conn);
  67. }
  68. /**********************/
  69. return FIDs;
  70. }
  71. public static String getUUID() {
  72. String FID = "";
  73. Connection conn = null;
  74. try {
  75. conn = DBUtils.getConnection();
  76. if (conn != null) {
  77. String sql0 = " SELECT NEWID() AS UUID ";
  78. Statement stm0 = conn.createStatement();
  79. ResultSet rs0 = stm0.executeQuery(sql0);
  80. while(rs0.next()) {
  81. FID = rs0.getString("UUID");
  82. }
  83. rs0.close();
  84. stm0.close();
  85. }
  86. }catch(Exception e) {
  87. e.printStackTrace();
  88. }finally {
  89. DBUtils.release(conn);
  90. }
  91. return FID;
  92. }
  93. public static void outImage(String FID,HttpServletResponse response) {
  94. byte[] bytes = getImage(FID);
  95. bytes = (bytes==null)?new byte[0]:bytes;
  96. response.setHeader("Pragma", "no-cache");
  97. response.setContentType("image/jpeg");
  98. ServletOutputStream ot = null;
  99. try {
  100. ot = response.getOutputStream();
  101. ot.write(bytes);
  102. ot.flush();
  103. ot.close();
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. public static byte[] getImage(String FID) {
  109. if (FID == null || FID.trim().equals("")) {
  110. return null;
  111. }
  112. byte[] bytes = null;
  113. Connection conn = null;
  114. BASE64Decoder decoder = new BASE64Decoder();
  115. try {
  116. conn = DBUtils.getConnection();
  117. if (conn != null) {
  118. boolean imgExist = false;
  119. String sql = " SELECT FID,imageObj FROM Base64Images WHERE FID = '" + FID + "' ";
  120. Statement stm = conn.createStatement();
  121. ResultSet rs = stm.executeQuery(sql);
  122. byte[] imgByte = null;
  123. while (rs.next()) {
  124. imgByte = (rs.getBytes("imageObj")==null)?null:rs.getBytes("imageObj");
  125. }
  126. //若根据FID在数据库找不到图片,则返回404.jpg
  127. if(imgByte == null) {
  128. String sql2 = " SELECT FID,imageObj FROM Base64Images WHERE FID = '4F40DD81-F262-4FB8-9463-7F3A29F2D8D1' ";
  129. Statement stm2 = conn.createStatement();
  130. ResultSet rs2 = stm2.executeQuery(sql2);
  131. while (rs2.next()) {
  132. imgByte = (rs2.getBytes("imageObj")==null)?null:rs2.getBytes("imageObj");
  133. }
  134. DBUtils.release(stm2, rs2);
  135. }
  136. DBUtils.release(stm, rs);
  137. if(imgByte != null) {
  138. imgExist = true;
  139. String imgByteStr = new String(imgByte, "UTF-8");
  140. bytes = decoder.decodeBuffer(imgByteStr);
  141. for (int i = 0; i < bytes.length; i++) {
  142. if (bytes[i] < 0) {
  143. bytes[i] += 256;
  144. }
  145. }
  146. }
  147. }
  148. } catch (Exception e) {
  149. e.printStackTrace();
  150. DBUtils.release(conn);
  151. }
  152. return bytes;
  153. }
  154. }

5.图片回显:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/256290
推荐阅读
  

闽ICP备14008679号