SpringMVC单个文件上传(上传到tomcat)
先导入jar包
因为写文件上传下载需要用到两个jar包 一个是io的一个是fileupload
<!--以下2个jar包⽤于⽂件上传--> <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileu pload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
在SpringMVC配置文件中添加一个Bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 设定文件上传的最大值为1024kb*1024kb -->
<property name="maxUploadSize" value="#{1024*1024}"/>
</bean>
前台我用的是jsp
isELIgnored="false 让el表达式生效 让JSP中的表达式不被当成字符串处理 ,isELIgnored的作用可以参考这个https://www.cnblogs.com/wl0000-03/p/6406582.html
from表单中的enctype的值一定一定要写成 "multipart/form-data“
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%
String path = request.getContextPath();
request.setAttribute("path",path);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${path}/file/fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="filename1"/>
<input type="submit" value="上传">
</form>
</body>
</html>
controller
/**
* 如果是原始对象处理文件上传下载的话得自己处理
* 现在是SpringMVC系统已经帮你处理成MulitipartFile的对象
* @param file
* @return
*/
@RequestMapping("/fileupload")
public String fileUpload(@RequestParam("filename1") MultipartFile file, HttpServletRequest request){
/*
* 想将MultipartFile对象封装的文件保存在tomcat上面
* 原始对象的做法就是new file("想要上传的文件的绝对路径")
* */
String filepath = request.getSession().getServletContext().getRealPath("/fileUpload");
System.out.println(filepath+"aaa");
System.out.println(file.getOriginalFilename());
/*重新命文件名 保证文件名唯一*/
String newFileName=(new Date()).getTime()+Math.ceil(Math.random()*1000)+file.getOriginalFilename();
//拷贝到的文件路径 separator这个关键字会自动识别当前的系统如果是win就是\\ 如果是Linux就是/
String path = filepath+ File.separator+newFileName;
File newFile = new File(path);
try {
file.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
}
return "fileUpload";
}
在Webapp目录下可以创建一个文件文件夹 目的是让你的tomcat目录下有这个文件夹 如果重启向项目没有的话,可以自己创建一个文件夹
如果你在webapp创建文件夹 一般情况下tomcat会自动把文件夹编译到进去
特别要注意 如果使用tomcat的话,项目会越来越大,如果是集群的话各个之间的同步还是个问题 如果是集群的话不建议使用tomcat 而是使用ftp服务器
还有一点 你的文件上传了之后不要清理target 如果清理完就你上传的所有的文件都没有了
出现这个错误说明你的文件夹没有被编译进来