首先pom文件引入相关依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
具体代码:
//获取文件存储路径
@Value("${filePath}")
private String filePath;
@RequestMapping(value ="/fileUp", method = RequestMethod.POST)
@ResponseBody
public void fileUploadOne(@RequestParam("file") MultipartFile file,@RequestParam("fileType") String fileType) {
// 获得原始文件名+格式
String fileName = file.getOriginalFilename();
//截取文件名
String fname = fileName.substring(0, fileName.lastIndexOf("."));
//截取文件格式
String format = fileName.substring(fileName.lastIndexOf(".") + 1);
//获取当前时间(精确到毫秒)
long MS = System.currentTimeMillis();
String timeMS = String.valueOf(MS);
//原文件名+当前时间戳作为新文件名
String videoName = fname + "_" + timeMS + "." + format;
String filelocalPath = "";
char pathChar = upfilePath.charAt(upfilePath.length() - 1);
Date date = new Date();
String dateOne = new SimpleDateFormat("yyyy/MM/dd/").format(date);
if (pathChar == '/') {
filelocalPath = upfilePath + dateOne;
} else {
filelocalPath = upfilePath + "/" + dateOne;
}
File f = new File(filelocalPath);
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(filelocalPath + videoName);
InputStream in = file.getInputStream();
//InputStream in = request.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
别忘了还需要在Application启动类中设置上传文件的大小:
//获取配置的上传文件的系统临时文件夹路径
@Value("${tempfilePath}")
private String tempfilePath;
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//允许上传的文件最大值
factory.setMaxFileSize("100MB");
/// 设置总上传数据总大小
factory.setMaxRequestSize("1024MB");
//设置临时文件路径,以防长时间不操作后删除临时文件导致报错
File f = new File(tempfilePath);
if (!f.exists())
f.mkdirs();
factory.setLocation(tempfilePath);
return factory.createMultipartConfig();
}