java 多图片上传与显示

来源:互联网 发布:知乎神回复2016 知乎 编辑:程序博客网 时间:2024/06/08 07:09
<!--1.首先是上传图片页面代码,这里应用了easyui-filebox文件框,
如果想上传多张图片,要用到multiple属性,给复制赋值为trueok就可以选择上传多张图片-->
<tr>
<td style="text-align: center;">上传图片:</td>
<td><input style="border-style: none" class="easyui-filebox" type="file"
name="file3" id="uploadFileIdcard" multiple=true data-options="width: 200" ></input></td>
</tr>

/*
*后台进行保存
*用SpringMVC注解@RequestParam()获取页面对象,用SpringMVC的MultipartFile进行文件上传,因为现在上传的是多张图片,我们给他定义成对象数组
*/
//增加功能
@RequestMapping(value = "add", method = RequestMethod.POST)
@ResponseBody
public String create(
@RequestParam(value = "file3", required = false) MultipartFile[] file3,
Model model,TblGyxglSub entity,HttpServletRequest request) {
String str3=savefile1(file3, request);
if(MyUtil.isnotempty(str3))
entity.setIdcard(str3);
tblgyxglsubservice.save(entity);
return "success";
}
//在保存操作的时候调用Savefile()方法进行解析图片路径
public String savefile1(MultipartFile[] file3,HttpServletRequest request){
//取得当前运行文件在服务器上的绝对路径.
String path=request.getRealPath("upload/img/group/zmzy/publicImg");
String filename="";
MultipartFile file = null;
File targetfile =null;
String newname="";
if (file3 != null && file3.length > 0) {
// 循环获取file数组中得文件
for (int i = 0; i < file3.length; i++) {
file = file3[i];
得到上传时的文件名
filename = file.getOriginalFilename();
//判断如果为空则返回null
if(!MyUtil.isnotempty(filename)){
return null;
}
//生成一个不允许重复的图片名称
String newnames=UUID.randomUUID().toString()+filename;
//创建成文件对象,然后准备进行下一步操作
targetfile=new File(path,newnames);
//判断文件是否存在,如果不存在则进行创建文件或目录
if(!targetfile.exists()){
targetfile.mkdirs();
}
try {
// 转存文件
file.transferTo(targetfile);
}catch(Exception e){
}
//把图片的路径追加到一个新字符串中,用||隔开
newname += newnames+"||";
}
}
return newname;
}
<!--图片以已保存,现在我们进行多图片显示-->

@RequestMapping(value="uplevelform/{id}")
public String uplevelform(@PathVariable("id") Integer id,Model model){
TblGyxglSub entity=tblgyxglsubservice.get(id);
String imgs = entity.getIdcard();
while (imgs.indexOf("||")>=0) {
imgs=imgs.replace("||", ",");
}
//把字符串转换成数组
String[] img = imgs.split(",");
model.addAttribute("img", img);
model.addAttribute("url", url);
model.addAttribute("action", "uplevel");
return shenheform;
}
//jsp页面jsp显示,很简单用jstl<c:forEach>遍历图片数组
<td style="text-align: center;">身份证:</td>
<td>
<ul id="dowebok3" class="dowebokk">
<li>
<c:forEach var ="idcard" items="${img}">
<center>
<img src="${ctx}/upload/img/group/zmzy/publicImg/${idcard}" alt="身份证">
</center>
</c:forEach>
</li>
</ul>
</td>
图片上传和现实显示完成