spring+mybaits+MySQL 实现图片上传并保存数据库
来源:互联网 发布:mac奶瓶双用粉底液色号 编辑:程序博客网 时间:2024/06/10 02:18
- 前言:在用Java做一些小项目的时候,为了少许的图片上传做一个文件服务器不值得,所以最快最简便的方式就是直接保存到数据库中。
因为部署的时候前后台有可能会分开部署公用一个库,所以把文件存到数据库是最好的办法之一。 - 建表
CREATE TABLE `tbl_file` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `case_id` bigint(20) DEFAULT NULL, `case_clazz` varchar(255) DEFAULT NULL, `images` mediumblob COMMENT '图片', `size` double DEFAULT NULL COMMENT '大小', `srcName` varchar(255) DEFAULT NULL COMMENT '名称', `unit` varchar(255) DEFAULT NULL COMMENT '单位', `create_time` datetime DEFAULT NULL, `is_delete` char(1) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8;
引入js(我这里用的是ajaxfileupload.js)
编码:
model、dao、mapper这里不再描述,用mybatis自行生成
service
@Overridepublic Long insertSelective(MultipartFile file) throws IOException { File fileEO=new File(); String fileName = file.getOriginalFilename(); fileEO.setSrcname(fileName); // 计算出文件的大小与现实单位(KB/MB) long bytes = file.getSize();// bytes String[] transferedArr = SXUnitUtils.byte2kbmb(bytes); Double size = Double.valueOf(transferedArr[0]); String unit = transferedArr[1]; fileEO.setSize(size); fileEO.setUnit(unit); //转换图片格式 :MultipartFile --> byte byte[] images = file.getBytes(); fileEO.setImages(images); fileEO.setCreateTime(new Date()); fileMapper.insertSelective(fileEO); return fileEO.getId(); }
3. controller
package com.bob.analyst.admin.controller;import java.io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.UnsupportedEncodingException;import javax.annotation.Resource;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.bob.analyst.model.File;import com.bob.analyst.service.FileService;import com.bob.analyst.util.DeleteType;@Controller@RequestMapping(value = "/file")public class FileController extends AjaxController { @Resource private FileService fileService; @RequestMapping(value = "/upload") @ResponseBody public Long upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws Exception { try { return fileService.insertSelective(file); } catch (Exception e) { e.printStackTrace(); throw e; } } @RequestMapping("showImage/{id}") @ResponseBody public byte[] showImage(@PathVariable("id") Long id, HttpServletResponse response) throws Exception { File fileEO=fileService.selectByPrimaryKey(id); if(fileEO==null||fileEO.getIsDelete().endsWith(DeleteType.IS_DELETE)){ throw new IllegalAccessException(); } byte[] images = fileEO.getImages(); String fileName =fileEO.getSrcname().toLowerCase(); if (fileName.lastIndexOf(".jpg") == -1 && fileName.lastIndexOf(".png") == -1 && fileName.lastIndexOf(".jpeg") == -1 && fileName.lastIndexOf(".gif") == -1 && fileName.lastIndexOf(".bmp") == -1) { BufferedInputStream bis = null; ServletOutputStream fos = null; byte[] buf = new byte[1024]; int size = 0; bis = new BufferedInputStream(new ByteArrayInputStream(images)); response.setContentType("multipart/form-data"); String realfilename = ""; try { //防止乱码 realfilename = new String(fileEO.getSrcname().getBytes("UTF-8"), "ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //设置文件名 response.setHeader("Content-Disposition", "attachment;fileName=" + realfilename); fos = response.getOutputStream(); while ((size = bis.read(buf)) != -1) fos.write(buf, 0, size); fos.close(); bis.close(); return null; } return images; } }
4. jsp+js 在jsp中引入ajaxFileUpload,网上有这个插件的教程,这里不再描述。 需要注意的地方是 : <input id="fileUpload" type="file" name="file" hidden="hidden"> id是在js中调用触发的,name是controller中对应的file:@RequestParam(value = "file") MultipartFile file 所以也是必须需要的。
function ajaxFileUpload() { //上传图片 $.ajaxFileUpload({ url: ctx+'/file/upload', //文件上传到哪个地址,告诉ajaxFileUpload secureuri: false, //一般设置为false fileElementId: 'fileUpload', //文件上传控件的Id <input type="file" id="fileUpload" name="file" /> dataType: 'TEXT', //返回值类型(大写)小写在某些浏览器可能不成功 success:function(ajaxResult){ //服务器响应成功时的处理函数 var fileId = ajaxResult.replace(/<.*?>/ig, '');//ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀 $("#uploadedImage").attr("src",ctx+"/file/showImage/"+fileId); $("#fileId").val(fileId); }, error:function(data, status, e){ //服务器响应失败时的处理函数 alert("图片上传失败,请联系管理员!"); } }) return false;}
阅读全文
1 0
- spring+mybaits+MySQL 实现图片上传并保存数据库
- spring上传图片并保存到数据库
- 上传图片并保存到数据库
- 上传图片保存到MySql数据库
- 图片上传并保存到数据库以及显示图片
- JavaWeb实现图片异步上传,在前台展示,并以二进制保存到数据库
- 用Seam实现:图片上传 + 保存到数据库 + 从数据库读出图片并显示到页面中
- 用Seam实现:图片上传 + 保存到数据库 + 从数据库读出图片并显示到页面中
- 上传图片到数据库并保存成Image格式
- php上传图片的代码并保存到数据库
- php上传图片的代码并保存到数据库
- php上传图片的代码并保存到数据库
- angularjs上传图片并转换成base64保存到数据库
- php上传图片并保存
- 使用ajaxfileupload插件实现异步上传并保存图片功能
- Java 后台实现上传图片的接收并保存
- php实现上传图片保存到数据库的方法
- 上传图片文件实现防伪图片水印并写入数据库
- [LeetCode] 求两个有序数组的中位数
- java动态加载
- Android 移除不用app
- PHP获取上周、本周、上月、本月、本季度、上季度时间方法大全
- 1030 Got error 139 from storage engine
- spring+mybaits+MySQL 实现图片上传并保存数据库
- groovy基础
- IBM Rational Software Architect V9.0安装
- Python3简单教程(四)迭代器与生成器
- ubuntu 常用命令:[1]ps 查看所有运行程序
- java基本类型数据所占字节数
- 探索 Linux 内存模型
- iOS资源的加载
- .net中字典的使用