SpringMVC實現多張圖片上傳例項
阿新 • • 發佈:2019-02-04
實現在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 <---- 資料庫路徑
你也可以自定義該路徑的。