首先,頁面代碼,這裏是upload.jsp:
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="name">
文件:<input type="file" name="multipartFile">
提交: <input type="submit" value="提交">
</form>
然後,我們在pom文件中添加文件上傳用到的依賴文件:
<!--文件上傳依賴-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
接着我們在spring-mvc.xml文件中配置文件上傳解析器:
<bean id="commonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳文件總大小-->
<property name="maxUploadSize" value="54280"/>
<!--編碼方式-->
<property name="defaultEncoding" value="UTF-8"/>
<!--單個上傳的文件大小-->
<property name="maxUploadSizePerFile" value="54280"/>
</bean>
之後編寫了文件上傳代碼:
@RequestMapping("/upload")
@ResponseBody
public void upload(String name, MultipartFile multipartFile) throws IOException {
System.out.println(name);
String filename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("F:\\"+filename));
}
這個時候你以爲萬事大吉,可以成功運行的時候,驚喜出現了,頁面給你來一個500…
idea控制檯給你來個null
我把代碼從頭順了一遍始終沒找到我的錯,於是乎,有技術朋友是真好!!!原來在文件解析器那裏ID必須要配置爲
multipartResolver
*哈哈,加粗是爲了醒目~~~~*
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳文件總大小-->
<property name="maxUploadSize" value="54280"/>
<!--編碼方式-->
<property name="defaultEncoding" value="UTF-8"/>
<!--單個上傳的文件大小-->
<property name="maxUploadSizePerFile" value="54280"/>
</bean>
大家千萬記得這個
坑
。加油,衝鴨。。。