1.首先我們在pom.xml中引入上傳文件所需要的依賴
<!-- 上傳文件所需要的依賴 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.在springmvc.xml中配置上傳文件所需要的配置信息
<!-- 多部分文件上傳 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
3.編寫文件上傳的請求發送視圖
<%@ page contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title>文件上傳</title>
</head>
<body>
<form action="mvc/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="上傳" />
</form>
</body>
</html>
4.編寫請求處理類
package com.yc.controllers;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@RequestMapping("mvc/upload")
public String fileUpload(@RequestParam MultipartFile myFile){
//getOriginalFilename()得到上傳的文件名
String path="G:/"+myFile.getOriginalFilename();
File newFile=new File(path);
//通過CommonsMultipartFile的方法直接寫文件
try {
myFile.transferTo(newFile);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return "uploadSuccess";
}
}
5.測試運行結果
OK,到此,我們得文件上傳功能就已經實現了,對於SpringMVC的基本配置大家可以去看我的另一篇博客“SpringMVC的HelloWorld實現”