环境配置
1.pom.xml
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
2.springmvc.xml
<!-- 配置文件解析器 -->
<!-- 注意:CommonsMultipartResolver的id是固定不变的,一定是multipartResolver,不可修改 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 如果上传后出现文件名中文乱码可以使用该属性解决 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 单位是字节,不设置默认不限制总的上传文件大小,这里设置总的上传文件大小不超过10M(10*1024*1024) -->
<property name="maxUploadSize" value="10485760"/>
<!-- 跟maxUploadSize差不多,不过maxUploadSizePerFile是限制每个上传文件的大小,而maxUploadSize是限制总的上传文件大小 -->
<property name="maxUploadSizePerFile" value="10485760"/>
</bean>
3.文件上传下载需要的jar包
链接:文件上传下载百度云链接
提取码:i2wd
实现代码
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
public class UploadFile {
public String UploadFile(HttpServletRequest req,MultipartFile file) throws IllegalStateException, IOException {
//文件名时间
SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-ss");
String res = sdf.format(new Date());
// uploads文件夹位置
String rootPath = req.getSession().getServletContext().getRealPath("/upload");
File rootPath1 = new File(rootPath);
if( !rootPath1.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建
rootPath1.getParentFile().mkdirs();
}
// 原始名称
String originalFileName = file.getOriginalFilename();
// 新文件l名
String newFileName = res+"_"+"sliver" + originalFileName.substring(originalFileName.lastIndexOf("."));
// 创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR) + "-" + (date.get(Calendar.MONTH)+1)+ "-" +(date.get(Calendar.DATE)));
// 新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
// 判断目标文件所在目录是否存在
if( !newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
System.out.println(newFile);
// 将内存中的数据写入磁盘
file.transferTo(newFile);
// 完整的url
String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName;
// System.out.println("------------------------------------------------------");
return originalFileName;
}
}