SSM框架实现多图片上传(单图片上传请看上篇博客)

我上一篇讲的是如何单文件上传,这一篇呢就讲多文件上传

第一步:首先得有一个文件夹,具体请看我上一篇博客,这篇就不说了。
第二部:上传图片的jsp页面中的代码:
<form action="${pageContext.request.contextPath}/addImg" method="post" enctype="multipart/form-data">
    <table >
        <tr>
            <td>上传图片:</td>
            <td><input type="file" name="file" /></td>	
            <td><input type="file" name="file" /></td>		
            <td><input type="file" name="file" /></td><!--这个name=“file”并不是数据库的属性名哦-->
        </tr>
    </table>
    <button type="submit" >保存</button>
</form>


显示图片的jsp页面中的代码:
<c:forEach var="b" items="${imgList}">
	<img src="http://localhost:8080/你的项目名/${b.img}">
</c:forEach>


第三步:

上传图片的Controller类的代码(这里面的“upload”就是我们创建的文件夹的名称):
@Controller
public class ImgController {
	@Autowired
	private ImgService imgService;

    @RequestMapping(value = "/addImg", method = RequestMethod.POST)
    private String addImg(Img img,@RequestParam(value="file",required=false) MultipartFile[] file,  
            HttpServletRequest request)throws Exception{   
	    //定义序号
	    int count=1;
	    for (MultipartFile mf : file) {
		if(!mf.isEmpty()){
			// 使用UUID给图片重命名,并去掉四个“-”
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			// 获取文件的扩展名
			String ext = FilenameUtils.getExtension(mf
			.getOriginalFilename());  
			// 设置图片上传路径
			String url = request.getSession().getServletContext()
			.getRealPath("/upload");
			System.out.println(url);
			// 以绝对路径保存重名命后的图片
			mf.transferTo(new File(url + "/" + name + "." + ext));
			// 把图片存储路径保存到数据库
			String path="upload/" + name + "." + ext;
			if(count==1){
				img.setImg1(path);
			}else if(count==2){
				img.setImg2(path);
			}else if(count==3){
				img.setImg3(path);
			}
		}  
		count++;
	}  
	imgService.addImg(img);
	return "redirect:/imgList";
}  

查询图片的Controller类的代码我上篇博客有讲到,具体可以翻看一下,这篇就不写了,都一样(还不是因为我懒)

还有什么不懂评论哟,我会回复的(`・ω・´)


  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值