About file uploading need two jar package
The setting of file upload form form
method: post mode must be set, as get request url parameter on the back, behind the carrying and url parameter is limited.
enctype: must be set to "multipart / form-data", form the default form in the form of key-value pairs.
1. The traditional way to upload files
Traditional file upload process:
- The browser to select the file to upload
- Background receives the request, parses
- After parsing decision whether to upload items
- If the item is uploaded, upload
the code
2. SpringMVC upload files
SpringMVC dispacherServlet employed utilizing multiple parsers to improve development efficiency, the file upload function, a file upload SpringMVC provides the CommonsMultipartResolver parser, through this class, the browser may parse the request to upload a file, the user upload request this parsing is omitted a process to improve the development efficiency.
- Upload interface
<--! 注意这里的name值,必须与后面处理上传请求的方法接收的参数相同 !-->
<form action="file/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传" >
</form>
- Upload the configuration file parser
<!-- 这里的bean的id 必须为 multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--这里还可以设置一些参数,如:文件上传大小的限制 -->
</bean>
- Processing method uploads
@RequestMapping("/fileupload2")
public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()){
file.mkdir();
}
// 获得到文件名
String filename = upload.getOriginalFilename();
filename = UUID.randomUUID().toString().replace("-","") + filename;
// 进行上传文件,上传结束之后,会自动删除掉临时文件
upload.transferTo(new File(path,filename));
return "success";
}
Upload find efficient than the traditional way a lot, SpringMVC file upload parser has been resolved to help users upload request.