【Java】SpringMVC实现多张图片上传实例
来源:互联网 发布:java 获取前一天日期 编辑:程序博客网 时间:2024/05/29 18:47
实现在Springmvc中上传图片功能很好实现。需求是将多张或单张图片上传至某个文件夹下,同时保存在数据库中和服务器上。现在我将会展现完整例子。
1、前提:在pom中添加相关的jar包。
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --><dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version></dependency>2、SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file。在applicationContext-mvc.xml中添加如下代码:
代码:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set the max upload size10MB --> <property name="maxUploadSize"> <value>10485760</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> <property name="defaultEncoding"> <value>utf-8</value> </property> </bean>
3. 在上传按钮时js代码:
/** * 点击添加图片 * 上传 多张图片 * 原生写法 * @param im * @returns */function uploadimgforlist(im){var fileTid = $(".ant-checkbox-checked[name=imgsubcheckbox]").children().eq(0).val();//获取文件夹的id if(typeof(fileTid) != "undefined"){ var path = imgpathchange(im); var file_name = $("input[name='fileImg']"); var addimg='<li>' +'<div class="uploadimg position-rv" onmouseover="showBtnImg(this)" onmouseout="hideBtnImg(this)">' +'<form id="formId" enctype="multipart/form-data" method="post">'//action="../../file/toUpLoadBacthHmImage.do?tid='+fileTid+'" +'</form>' /*+ '<img src="'+path+'">' + '<div id="" class="position-ab imghandle dpnone">' + '<i class="iconfont icon-download" onclick="downloadThisImage(this);"></i>' + '<i class="iconfont icon-delete pull-right deleteimgsigle" onclick="deleteimgsigle(this)"></i>' + '</div>'*/ +'</div>' +'</li>'; $("#imgshowlist").append(addimg); $("#formId").append(file_name); var options = { url: '../../file/toUpLoadBacthHmImage.do', type: "post", dataType: 'json', data:{tid:fileTid}, success:function(data){ if(data.result == true){ alert("上传成功"); location.reload(); }else { alert("上传失败");} }, error:function(data,msg){ $.error("上传信息失败" + msg); } } $("#formId").ajaxSubmit(options); }else {alert("请先选择文件夹,在进行添加图片!");}}4、实现上传功能的Controller类方法:
/** * 多张图片上传(含单张) * @param request * @param response * @param model * @return * @author zhangsq */@RequestMapping("/toUpLoadBacthHmImage.do")public @ResponseBody Map<String, Object> toUpLoadBacthHmImage(HttpServletRequest request, HttpServletResponse response,ModelMap model,String tid,@RequestParam("fileImg") MultipartFile[] multipartfiles) throws IllegalStateException, IOException{Map<String, Object> map = new HashMap<String, Object>(); HmFile fileBean = hmFileService.findByTidFilesInfo(tid); /** 得到图片保存目录的真实路径 **/String realpath = properties.getProperty("file.acpath.server");/** 构建图片保存的目录 **/String filedir =File.separator+ SpellUtil.getFirstSpell(fileBean.getFileName());String filelocationdir = realpath + filedir;/** 根据真实路径创建目录 **/File logoSaveFile = new File(filelocationdir);if (!logoSaveFile.exists()){logoSaveFile.mkdirs();} boolean doFlag;if(null != multipartfiles && multipartfiles.length > 0){ //MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //List<MultipartFile> iter = multiRequest.getFiles("file"); try { for(MultipartFile picFile : multipartfiles){ //MultipartFile picFile = multiRequest.getFile(iter.next()); if(null != picFile && null != picFile.getOriginalFilename() && !"".equals(picFile.getOriginalFilename().trim()) && !"null".equals(picFile.getOriginalFilename().trim())){ synchronized(HmFileImageController.this){ String imagename = new SimpleDateFormat("yyyyMMddHHmmss") .format(new Date()).concat(picFile.getOriginalFilename()); String filename = filelocationdir + File.separator +imagename; File file = new File(filename); picFile.transferTo(file);//上传至服务器 //将文件图片插入数据库 HmImage imgBean = new HmImage(); imgBean.setTid(UUIDUtil.getUUID()); imgBean.setHid(tid); long curTimeStamp = System.currentTimeMillis(); String fileACPath = properties.getProperty("file.acpath.views.server"); String spell = SpellUtil.getFirstSpell(fileBean.getFileName()); fileACPath=String.format(fileACPath,spell,imagename,curTimeStamp); imgBean.setFilePath(fileACPath); //imgBean.setFilePath(fileACPath.replaceAll("/", "\\\\")); String tid_insert = hmImagesService.insertSelective(imgBean);//保存在数据库中 hmFileService.updateByTidUpdateTimes(tid);//更新文件夹的时间 map.put("tid_insert", tid_insert); } } } doFlag = true; } catch (IllegalStateException e) {e.printStackTrace();doFlag = false;} catch (IOException e) {e.printStackTrace();doFlag = false;} //遍历并保存文件 map.put("result", doFlag); } return map;}tid:是某个文件夹的id。该功能实现了多张图片上传,一是可以将图片保存在数据库(存储图片的路径),二是将图片存储在服务器上。
附上配置文路径文件:
file.acpath.server=/home/weihu/img_resource/school_web <---- 服务器路径file.acpath.views.server=http://www.zxctinfo.com:8080/school_web_img/%s/%s?t=%s <---- 数据库路径
你也可以自定义该路径的。
阅读全文
0 0
- 【Java】SpringMVC实现多张图片上传实例
- springmvc上传多张图片
- freemarker+springMVC+ajaxfileupload实现异步图片上传(多张)
- SpringMvc MultipartFile 多张图片文件上传
- Java 上传 多张图片
- springmvc多图片上传实例
- java struts中实现上传多张图片代码
- 实现多张图片上传的接口
- AFNetworking实现多张图片上传
- js实现上传多张图片
- springmvc上传图片实例
- java选中多张图片上传
- 多张图片上传
- 上传多张图片
- 上传多张图片
- 多张图片上传
- Post同时上传多张图片和数据实例
- SpringMVC实现图片上传
- 通过js来获取前多少天的或者后多少天的日期
- 10个值得深思的_PHP_面试问题
- kotlin初窥之Kotlin Android Extensions
- ASP.NET Core 中间件之压缩、缓存
- 结辩为什么要煽情?
- 【Java】SpringMVC实现多张图片上传实例
- 算法导论程序14-快速排序的随机化版本(Python)
- 二叉排序树数值最接近节点
- 用队列解决杨辉三角问题
- ASP.NET Core HTTP 管道中的那些事儿
- README
- 面试:----maven怎么添加自己的jar包
- Delphi XE10 给地图层上面添加Android原生控件
- 5.24~6.4-Python-语言及其应用-笔记-代码结构