1 准备工作
1.1 导入文件上传需要的依赖
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
1.2 在springMvc.xml文件中配置文件上传所需要的组件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8">property>
<property name="maxUploadSizePerFile" value="5242880">property>
<property name="resolveLazily" value="true">property>
bean>
1.3 给上传的文件夹设置完全控制权限

2 创建FileController类
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class FileController {
@RequestMapping("fileupload")
public String sc(MultipartFile img) throws IOException {
try {
String filename = img.getOriginalFilename();
System.out.println("文件名:"+filename);
File file=new File("F:\\2\\temp",filename);
img.transferTo(file);
} catch (Exception e) {
e.printStackTrace();
}
return "file";
}
}
- 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
3 给tomcat配置静态资源访问路径
3.1 点击External Source

3.2 选择你要配置的路径

3.3 更改访问地址并点击ok按钮

4 创建file.jsp界面(用于上传文件)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--这个imgs的地址就是刚刚配好的那个F:\2\temp的地址--%>
5 测试代码
5.1 提交前

5.2 提交后

5.3 上传后对应的文件夹展示截图
