SpringMVC通过MultipartResovler(接口)实现的文件上传,实现类:CommonsMultipartResovler

一、导入jar包

commons-fileupload-1.2.1.jar
commons-io-2.0.jar

二、在SpringMVC配置文件中配置MultipartResovler

<!-- 配置MultipartResovler -->
<bean id="multipartResolver" 
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"></property>
    <property name="maxUploadSize" value="102400"></property>
</bean>

三、编写前端上传文件的代码

<form action="testFileUpload" method="POST" enctype="multipart/form-data">
    File: <input type="file" name="file"/>
    Desc: <input type="text" name="desc"/>
    <input type="submit" value="Submit"/>
</form>

四、编写Controller

@ResponseBody
@RequestMapping("/test")
public String test(@RequestParam String desc,
		@RequestParam MultipartFile file) throws Exception {
		
    /**
     * 若目录不存在则创建目录
     */
	String rootPath = "D:";
    String filePath = rootPath + "/";
    File dir = new File(filePath);
    if (!dir.isDirectory())
       dir.mkdir();

    /**
     * 保存文件到本地
     */
    String fileOriginalName = file.getOriginalFilename();
    String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + 
            fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
    File writeFile = new File(filePath + newFileName);
    file.transferTo(writeFile);
        
    return newFileName;
}