【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      <---- 数据库路径

你也可以自定义该路径的。