SpringMVC上传多个文件

form表单要加上enctype="multipart/form-data" 多部件类型

在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。

 

先加入上传文件需要的jar包

然后再在springmvc.xml中配置multipart类型解析器。

<!-- .文件上传的配置 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>5242880</value>
		</property>
	</bean>

建议在tomcat里配置虚拟路径,方便后期更新,以及减轻tomcat的负载。

配置虚拟路径方法:在tomcat下conf下的server.xml的Host标签里加入如下内容:

前端页面代码:

<form action="<%=GetPath.getThePath(request) %>saveBook.action" method="post" enctype="multipart/form-data">
		<table width="1070" align="center" >
			<tr style="background-color:#e4e4e4">
				<td>商品编号:</td>
				<td><input type="text" name="bookid"/></td>
			</tr>
			<tr style="background-color:#e4e4e4">
				<td>商品名称:</td>
				<td><input type="text" name="bookname"/></td>
			</tr>
			<tr style="background-color:#e4e4e4">
				<td>商品价格:</td>
				<td><input type="text" name="bookprice"/></td>
			</tr>
<tr style="background-color:#e4e4e4">
				<td>上传图片:</td>
				<td><input type="file" name="file"/></td>
			</tr>
<tr style="background-color:#e4e4e4">
				<td>上传大图片:</td>
				<td><input type="file" name="file"/></td>
			</tr>
<tr style="background-color:#e4e4e4">
				<td colspan="2"><input type="submit" value="添加新书籍"/>
				<input type="reset" value="重置"/></td>
			</tr>
		</table>
	</form>

专门写一个上传文件的方法,方法上传多个文件时候调用:

/**
	 * 文件上传的方法
	 */
	public String saveFile(MultipartFile multipartFile){
		String originalName=multipartFile.getOriginalFilename();
		String path="E:\\graduationPic\\";
		String newName=IdName.getIdName()+originalName.substring(originalName.lastIndexOf("."));
		File file=new File(path+newName);
		
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return "/images/"+newName;
	}

controller代码:

/*
	 * 添加新书,其中包含文件上传
	 */
	@RequestMapping(value="saveBook",method=RequestMethod.POST)
	public String saveBook(Book book,@RequestParam("file")MultipartFile[] file){
		
		if(file.length>0){
			String bookimg=saveFile(file[0]);
			String homeimg=saveFile(file[1]);
			book.setSendBookTime(IdName.getCurrentTime());
			book.setBookimg(bookimg);
			book.setHomeImage(homeimg);
			System.out.println(bookimg);
			System.out.println(homeimg);
		}
		
		
		
		System.out.println(book);
		iBookService.addBook(book);
		return "houtaiPage/mainPage/index.jsp";
	}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值