准备工作:添加文件上传依赖
<dependencies>
<!-- 文件上传依赖 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- 高版本servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
测试
1、编写文件上传表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%--文件上传表单--%>
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
2、在applicationContext.xml配置文件下配置
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单内容,默认为ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--文件上传大小限制,单位为字节(10485760=1m)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
3、 编写文件上传controller
@RestController
public class FileController {
//保存上传文件方法1
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名:file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,返回首页
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";//重定向返回要重新加载服务器
}
System.out.println("上传文件名:" + uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在再创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址" + realPath);
InputStream is = file.getInputStream();//文件输入流
FileOutputStream fos = new FileOutputStream(new File(realPath, uploadFileName));//文件输出流
//读写输出(使用缓冲区)
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1){
fos.write(buffer,1,len);
fos.flush();
}
fos.close();
is.close();
return "redirect:/index.jsp";
}
//方法2:采用file.TransferTo来保存上传文件
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();//文件不存在则创建
}
//上传文件地址
System.out.println("上传文件保存地址:" + realPath);
//通过CommonsMultipartFile的方法直接写入到本地文件中
file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
return "redirect:/index.jsp";
}
}
要把web目录放在src/main目录下才不用导包,这是maven的约定,因为我们web文件和src同级
所有(每次需要将所有依赖 在项目结构中再导入一次到web-inf中)