SpringMVC文件上传的配置实例详解

时间:2022-03-14 10:30:34

记述一下步骤以备查。

准备工作:

需要把Jakarta Commons FileUpload及Jakarta Commons io的包放lib里。

我这边的包是:

commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar

然后在spring-servlet.xml进行multipartResolver配置,不配置好上传会不好用。

?
1
2
3
4
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><value>100000</value></property>
<property name="defaultEncoding"><value>UTF-8</value></property>
</bean>

接下来就是页面了:

注意Form的写法和文件上传组件的写法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form action="uploadPosdetailFile.html" method="post" ENCTYPE="multipart/form-data">
<div class="form" >
<p>
<span class="req"><input id="startDateTxt" name="startDateTxt" class="field size4" title="Enter the date" /></span>
<label>Start Date: <span>(Date format:MM/dd/yyyy,eg:01/01/2014)</span></label>
</p>
<p>
<span class="req"><input id="endDateTxt" name="endDateTxt" class="field size4" title="Enter the date" /></span>
<label>End Date: <span>(Date format:MM/dd/yyyy,eg:12/25/2014)</span></label>
</p>
<p>
<span class="req"><input type="file" name="uploadFileCtrl" class="field size4" title="Choose the file" /></span>
<label>Upload file: <span>(click browse to choose)</span></label>
</p>
</div>
<div class="buttons">
<input id="queryBtn" type="Submit" class="button" value="Submit" />
</div>
</form>

再在控制器里写处理代码,注意参数和页面控件的对应关系:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@RequestMapping(value="/uploadPosdetailFile")
public String uploadPosdetailFile(@RequestParam("startDateTxt") String startDateTxt,
@RequestParam("endDateTxt") String endDateTxt,
@RequestParam("uploadFileCtrl") MultipartFile file,HttpServletRequest request,HttpServletResponse response){
try {
System.out.println("@@@@@@@@@1.startDateTxt="+startDateTxt);
System.out.println("@@@@@@@@@2.endDateTxt="+endDateTxt);
System.out.println("@@@@@@@@@3.file="+file.getOriginalFilename());// 得到上传文件的文件名
if(file.isEmpty()==false){
InputStream is=file.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String s;
while((s=br.readLine())!=null ){
System.out.println(s);
}
br.close();
isr.close();
is.close();
}
return "/pages/posdetail/uploadposdetailresult/index.jsp";
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
request.setAttribute("error", e.getClass());
request.setAttribute("reason", e.getMessage());
StackTraceElement[] arr=e.getStackTrace();
request.setAttribute("stackTraceElements", arr);
return "pages/error/index.jsp";
}
}