1.前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="upload/upload.do" method="post" enctype="multipart/form-data"> <p>请选择您要上传的文件</p> <p> <input type="file" name="file" onchange="preview(this);"/> </p> <!-- 这个是在上传之前回显图片图片展示 --> <div id="preview"> <!--这个是为了将页面返回的图片展示出来的.默认隐藏--> <img style="width: 100px; height: 100px;display:none" id="imgHidden" /> </div> <p> <input type="submit" value="上传"/> </p> </form> </body> <script type="text/javascript"> function preview(file){ var prevDiv = document.getElementById('preview'); if(file.files && file.files[0]){ var reader=new FileReader(); reader.onload=function(evt){ prevDiv.innerHTML='<img style="width: 100px;height: 100px;" src="' + evt.target.result + '" />'; } reader.readAsDataURL(file.files[0]); }else{ prevDiv.innerHTML = '<div class="img" style="width: 100px;height:100px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>'; } } </script> </html>
2.展示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>展示图片</title> </head> <body> <table> <tr><th>名字</th><th>说明</th><th>图片预览</th></tr> <c:forEach items="${pictureList}" var="item"> <tr><td>图片</td><td>${item.imgId}</td><td><img src="data:image/png;base64,${item.imgCode}" height="200px" width="500px"/></td></tr> </c:forEach> </table> </body> </html>
3.后台代码
package cn.tedu.controller; import cn.tedu.domain.TPicture; import cn.tedu.service.TPictureService; import com.fasterxml.jackson.databind.util.JSONPObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import sun.misc.BASE64Encoder; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * @author jiyiyuan * @date 2021/1/23-15:09 */ @RequestMapping("/upload") @Controller public class UploadController2 { @Autowired private TPictureService tPictureService; @RequestMapping(value = "upload.do") public ModelAndView upload(ModelMap modelMap, HttpServletRequest req, TPicture p, @RequestParam("file") MultipartFile file) throws Exception { ModelAndView modelAndView = new ModelAndView(); if (file != null) {// 判断上传的文件是否为空 String path = null;// 文件路径 String type = null;// 文件类型 String fileName = file.getOriginalFilename();// 文件原名称 System.out.println("上传的文件原名称:" + fileName); // 判断文件类型 type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null; if (type != null) {// 判断文件类型是否为空 if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) { // 项目在容器中实际发布运行的根路径 //String realPath = req.getSession().getServletContext().getRealPath("/"); String realPath="D:\\upload\\picture\\"; // 自定义的文件名称 String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName; // 设置存放图片文件的路径 path = realPath + trueFileName; System.out.println("存放图片文件的路径:" + path); //D:\java\tomcat\apache-tomcat-8.0.50\webapps\ssm_project\1611388970321douwei.jpg // 转存文件到指定的路径 file.transferTo(new File(path)); /* InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(path); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); String a = encoder.encode(data); */ String imgCode = encodeBase64File(path); p.setImgCode(imgCode); p.setImgPath(path); p.setNo(1); tPictureService.saveTPicture(p); String ad = realPath + trueFileName; modelAndView.addObject("msg", "文件成功上传到指定目录下"); modelAndView.setViewName("success"); } else { modelAndView.addObject("msg", "不是我们想要的文件类型,请按要求重新上传"); modelAndView.setViewName("defeat"); } } else { modelAndView.addObject("msg", "文件类型为空"); modelAndView.setViewName("defeat"); } } else { modelAndView.addObject("msg", "没有找到相对应的文件"); modelAndView.setViewName("defeat"); } return modelAndView; } @RequestMapping("showPicture.do") public ModelAndView showPicture(){ ModelAndView modelAndView=new ModelAndView(); List<TPicture> pictureList=tPictureService.getPictureList(); modelAndView.addObject("pictureList",pictureList); modelAndView.setViewName("show"); return modelAndView; } /** * 编码 * @param path * @return */ public static String encodeBase64File(String path){ // 读取文件 File file = new File(path); // 声明输入流 FileInputStream inputFile = null; // 声明字节数组 byte[] buffer = null; try { inputFile = new FileInputStream(file); // 创建字节数组 buffer = new byte[(int) file.length()]; // 输入 inputFile.read(buffer); } catch (Exception e) { e.printStackTrace(); }finally { try { inputFile.close(); } catch (IOException e) { e.printStackTrace(); } } // 解码 return new BASE64Encoder().encode(buffer); } }
4.数据库
5.补充:
三 base64文件编码解码
编码后返回编码的字符串
/* * * @Author lsc * <p> base64编码 </p> * @Param [path] * @Return java.lang.String 返回编码后的字符串 */ public static String encodeBase64File(String path){ // 读取文件 File file = new File(path); // 声明输入流 FileInputStream inputFile = null; // 声明字节数组 byte[] buffer = null; try { inputFile = new FileInputStream(file); // 创建字节数组 buffer = new byte[(int) file.length()]; // 输入 inputFile.read(buffer); } catch (Exception e) { e.printStackTrace(); }finally { try { inputFile.close(); } catch (IOException e) { e.printStackTrace(); } } // 解码 return new BASE64Encoder() .encode(buffer); }
也可以将字节数组放入输入流进行对象存储
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
3.2 解码
将编码后的字符串重新转为文件
/* * * @Author lsc * <p> base64解码 </p> * @Param [base64Code, targetPath] 将编码后的字符串解码为文件 * @Return void */ public static void decodeBase64File(String base64Code, String targetPath) { // 输出流 FileOutputStream out =null; // 将base 64 转为字节数字 byte[] buffer = new byte[0]; try { buffer = new BASE64Decoder().decodeBuffer(base64Code); // 创建输出流 out = new FileOutputStream(targetPath); // 输出 out.write(buffer); } catch (Exception e) { e.printStackTrace(); }finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
3.3测试示例
@Test public void test(){ try { // 文件路径 String filePath = "C:\\mydata\\generator\\世界地图.png"; // 编码 String encodeBase64File = encodeBase64File(filePath); // 剔除base64声明头 String code = encodeBase64File.replace("data:image/png;base64,", ""); //解码 decodeBase64File(code,"C:\\mydata\\generator\\base64.png"); } catch (Exception e) { e.printStackTrace(); } }