SpringMVC实现文件上传
- 现在html文件中定义form表单,并且enctype要设置为"multipart/form-data"
<h3>Spring Mvc文件上传</h3>
<form action="file/springMvcRequest" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpLoad">
<br>
<input type="submit" value="提交">
</form>
- 控制器接收表单的数据并进行处理
- 使用common.io和common.fileupload实现文件上传
- 引入maven依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- controller中的控制器解析表单中传过来的数据并解析成文件
@RequestMapping(path = "/request")
public String fileUpLoad(HttpServletRequest request) throws Exception {
//先创建一个文件夹
//上传的位置
//存储在servlet容器中
String realPath = request.getSession().getServletContext().getRealPath("/upload/");
File file=new File(realPath);
if (!file.exists()){
file.mkdirs();
}
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//解析request请求
List<FileItem> fileItems = upload.parseRequest(request);
//遍历文件项
for (FileItem item:fileItems){
if (item.isFormField()){
String name=item.getFieldName();
System.out.println(name);
String value=item.getString("UTF-8");
System.out.println(value);
//如果是表单数据
}else {
String fileName=item.getName();//获得文件名称
String s=UUID.randomUUID().toString().replace("-","");
fileName=s+"_"+fileName;
item.write(new File(realPath,fileName));
//删除临时文件
/*item.delete();*/
}
}
return "success";
}
- 通过配置spring mvc中的文件解析器实现文件上传
<!--配置文件解析器:
这个文件解析器的作用就是当请求被前端控制器拦截的时候,就把请求中的文件文件项解析成 MultipartFile
类型的文件,我们只需要在控制器的参数中注入 MultipartFile fileUpLoad就行
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000"/>
</bean>
<!--解除静态资源的拦截-->
<mvc:resources mapping="/js/**" location="/js/"/>
<!--打开mvc注解:在这里配置了处理器映射和处理器适配器-->
<mvc:annotation-driven conversion-service="serviceFactory"/>
controller
@RequestMapping(path = "/springMvcRequest")
public String MvcFileUpLoad(HttpServletRequest request, MultipartFile fileUpLoad) throws IOException {
//先创建一个文件夹
//上传的位置
String realPath = request.getSession().getServletContext().getRealPath("/upload/");
File file=new File(realPath);
if (!file.exists()){
file.mkdirs();
}
String fileName=fileUpLoad.getOriginalFilename();//文件名
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName=uuid+"_"+fileName;
fileUpLoad.transferTo(new File(realPath,fileName));
return "success";
}
SpringBoot实现文件上传
- 用于spring boot已经帮我们配置springmvc的自动配置类了
- 我们只需要注入web启动器就行了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
其他就和默认的springmvc一样了