SpringMVC多张最简单的上传功能(前台+后台)
改功能基于实战项目,后台:mybatis+SpringMVC,前台:freemarker模板+datatables
前台
<div class="portlet-body form">
<form id="inputForm" class="form-horizontal" role="form" action="${ctx}/admin/driver/upphoto.json" method="post"
enctype="multipart/form-data">前台上传必须写标红字体
<input type="hidden" id="driverId" name="id" value="${driver.id}">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">
照片:
</label>
<div class="col-md-9">
<input type="file" class="form-control" id="photo" name="file" placeholder="照片" accept="image/png,image/gif,image/jpg,image/jpeg">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">
驾驶证照片:
</label>
<div class="col-md-9">
<input type="file" class="form-control" id="idPhoto" name="file" placeholder="驾驶证照片" accept="image/png,image/gif,image/jpg,image/jpeg">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">
驾驶证反面照片:
</label>
<div class="col-md-9">
<input type="file" class="form-control" id="idPhotoBack" name="file" placeholder="驾驶证反面照片" accept="image/png,image/gif,image/jpg,image/jpeg">
</div>
</div>
</div>
<div class="form-actions right">
<button id="btnCancel" type="button" class="btn default">返回</button>
<@shiro.hasPermission name="admin:driver:add">
<input id="btnSubmit" type="submit" class="btn green" value="确定">
</@shiro.hasPermission>
</div>
</form>
</div>
后台
/**
* @RequestParam("file")指定
* 上传图片处理
*
*/
@RequiresUser//判断用户是否登录
@RequiresPermissions("admin:driver:add")//权限问题
@RequestMapping(value = "/upphoto", method = RequestMethod.POST)
public String upphoto(HttpServletRequest request, @RequestParam(value="file",required = false)MultipartFile file[],Driver target, Long id){
//根据id获取相应对象
target=this.driverService.findById(id);
//获取项目路径
ServletContext sc=request.getSession().getServletContext();
//设置储存位置
String path=sc.getRealPath("/upload")+"\\";
//遍历
for(int i=0; i<file.length;i++){
if(!file[i].isEmpty()){
try {
//获取照片原始名称
String photoName=file[i].getOriginalFilename();
//扩展名
String extName = photoName.substring(photoName.lastIndexOf("."));
//防止图片名称冲突,中文乱码等问题重命名
photoName = System.nanoTime() + extName;
//储存实体类
if(i==0){
target.setPhoto("..\\..\\upload\\"+photoName);//储存到数据库的是相对路径,如果想写绝对路径括号内修改为(path+photoName)
}else if(i==1){
target.setIdPhoto("..\\..\\upload\\"+photoName);
}else{
target.setIdPhotoBack("..\\..\\upload\\"+photoName);
}
//创建实际路径
file[i].transferTo(new File(path+photoName));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//保存到数据库
this.driverService.save(target);
return "admin/driver/list";
}
使用绝对路径存储图片,在前台页面读取图片的时候会出现一个很大的问题,因为目前大部分浏览器安全性非常高,不支持绝对路径的读取。
使用相对路径存储图片,使用普通的tomcat启动方式,也会取不出来图片,但是在maven build 启动的话,是没有任何问题的。
解决绝对路径读取的问题,在网上看到很多使用tomcat虚拟路径,但是使用的时候并没有达到预期效果,所以暂时没有解决。

浙公网安备 33010602011771号