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";
}