package cc.mrbird.febs.video.controller; import cc.mrbird.febs.common.entity.FebsResponse; import cc.mrbird.febs.common.exception.FebsException; import cn.hutool.core.lang.UUID; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartRequest; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /** * @author wzy * @date 2021-12-14 **/ @Slf4j @RequestMapping(value = "/common") @RestController @RequiredArgsConstructor public class CommonController { @Value("${system.images.path}") private String baseSavePath; @Value("${system.images.url}") private String baseUrl; @RequestMapping(value = "/upload") public FebsResponse upload(MultipartRequest request) throws IOException { // 保存路径 /Users/helius/Desktop/ // baseSavePath = "/Users/helius/Desktop/"; // 访问路径 // baseUrl = "http://localhost:1234/"; List visitPathes = updateImg(request); return new FebsResponse().success().data(visitPathes); } private List updateImg(MultipartRequest request) { // 检查目录 File uploadDir = new File(baseSavePath); if (!uploadDir.isDirectory()) { uploadDir.mkdir(); } Map fileMaps = request.getFileMap(); List visitPathes = new ArrayList<>(); for (String key : fileMaps.keySet()) { MultipartFile file = fileMaps.get(key); // 拼接64位文件名 String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); String newFileName = UUID.randomUUID().toString() + "." + fileExt; Map fileUrlMap = fileUrl(baseSavePath, baseUrl); String savePath = fileUrlMap.get("savePath"); String saveUrl = fileUrlMap.get("saveUrl"); File uploadedFile = new File(savePath, newFileName); try { FileCopyUtils.copy(file.getBytes(), uploadedFile); } catch (IOException e) { throw new FebsException("上传失败"); } // 图片访问地址 String visitPath = saveUrl + newFileName; visitPathes.add(visitPath); } return visitPathes; } private Map fileUrl(String savePath, String saveUrl) { Map fileUrlMap = new HashMap<>(); // 创建日期文件夹 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + File.separatorChar; saveUrl += ymd + File.separatorChar; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } fileUrlMap.put("savePath", savePath); fileUrlMap.put("saveUrl", saveUrl); return fileUrlMap; } }