package com.kwan.springbootkwan.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; 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; /** * 文件上传 * * @author : qinyingjie * @version : 2.2.0 * @date : 2022/12/19 16:07 */ @RestController public class FileUploadController { /** * 单文件上传 * * @param uploadFile * @param req * @return */ @PostMapping("/upload") public String upload(MultipartFile uploadFile, HttpServletRequest req) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String realPath = req.getSession().getServletContext().getRealPath("/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() + "/uploadFile/" + format + newName; return filePath; } catch (IOException e) { e.printStackTrace(); } return "文件上传失败"; } /** * 多文件上传 * * @param uploadFiles * @param req * @return */ @PostMapping("/uploadBatch") public String uploadBatch(@RequestPart("uploadFile") MultipartFile[] uploadFiles, HttpServletRequest req) { //遍历 uploadFiles 数组分别存储 return "success"; } }