SpringBoot单文件和多文件上传
先创建一个UploadFileService接口,封装好单文件上传的文件接收方法,多文件上传使用循环调用接口即可
单文件上传
一、首先:UploadFileService接口
package edu.zhku.fire_ant_project.service;
import edu.zhku.fire_ant_project.comment.Result;
import edu.zhku.fire_ant_project.entity.Slideshow;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class UploadFileService {
@Autowired
private HttpServletRequest req;
public String saveUploadFile(MultipartFile uploadFile) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
// 上传的文件将保存在项目运行目录下的 uploadFile 文件夹,
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");//工程目录创建
// 并且在 uploadFile 文件夹中通过日期对上传的文件归类保存
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
// 对上传的文件重命名,避免文件重名
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
// 文件保存
uploadFile.transferTo(new File(folder, newName));
// 返回上传文件的访问路径
String filePath = req.getScheme() + "://" + req.getServerName()
+ ":" + req.getServerPort() + "/fire_ant_project/uploadFile/" + format + newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
二、单文件上传
直接调用即可:
@PostMapping("/uploadFile")
public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile uploadFile){
Map map=new HashMap<>();
try {
String filepath = uploadFileService.saveUploadFile(uploadFile);
map.put("filepath",filepath);
} catch (NullPointerException e) {
map.put("filepath","没有找到文件");
}
return map;
}
多文件上传
直接调用循环函数即可
@PostMapping("/uploadFile")
public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile[] uploadFile){
Map map=new HashMap<>();
try {
if (uploadFile.length > 0) {
for (int i = 0; i < uploadFile.length; i++) {
String filepath = uploadFileService.saveUploadFile(uploadFile[i]);
map.put("filepath", filepath);
}
}else {
map.put("filepath","没有找到文件");
}
} catch (NullPointerException e) {
map.put("filepath","没有找到文件");
}
System.out.println(map);
return map;
}
文件上传页面:
action:项目的相对路径
单文件上传:去掉multiple
多文件上传:加上multiple