重构uploadImage方法,添加错误处理。v1

Signed-off-by: zup <jiu3295282258@163.com>
main
laptop_zup 9 months ago committed by zup
parent 3fea87e548
commit 4147bec886

@ -19,8 +19,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* @Author: - *@Author zup
* @Date: 2019/12/15 23:46 *@Date: 2024/12/16
*/ */
@RestController @RestController
@RequestMapping("file") @RequestMapping("file")
@ -33,29 +33,57 @@ public class FileController {
*/ */
@RequestMapping("uploadImage") @RequestMapping("uploadImage")
public Map<String, Object> uploadImage(MultipartFile mf) { public Map<String, Object> uploadImage(MultipartFile mf) {
// 1. 得到文件名 Map<String, Object> map = new HashMap<>();
// 检查 MultipartFile 是否为空
if (mf == null || mf.isEmpty()) {
map.put("error", "上传文件为空");
return map;
}
// 得到文件名原始名
String oldName = mf.getOriginalFilename(); String oldName = mf.getOriginalFilename();
// 2. 根据旧的文件名生成新的文件名
String newName = AppFileUtils.createNewFileName(oldName); // 检查文件名是否为空
// 3. 得到当前日期的字符串 if (oldName == null || oldName.trim().isEmpty()) {
String dirName = DateUtil.format(new Date(), "yyyy-MM-dd"); map.put("error", "文件名为空");
// 4. 构造文件夹 return map;
File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName);
// 5. 判断当前文件夹是否存在
if (!dirFile.exists()) {
// 如果不存在则创建新文件夹
dirFile.mkdirs();
} }
// 6. 构造文件对象
File file = new File(dirFile, newName + "_temp");
// 7. 把 mf 里面的图片信息写入 file
try { try {
// 根据旧的文件名生成新的文件名
String newName = AppFileUtils.createNewFileName(oldName);
// 得到当前日期的字符串
String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
// 构造文件夹
File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName);
// 判断当前文件夹是否存在
if (!dirFile.exists()) {
// 如果不存在则创建新文件夹
if (!dirFile.mkdirs()) {
map.put("error", "无法创建上传路径:" + dirFile.getAbsolutePath());
return map;
}
}
// 构造文件对象
File file = new File(dirFile, newName + "_temp");
// 把 mf 里面的图片信息写入 file
mf.transferTo(file); mf.transferTo(file);
} catch (IllegalStateException | IOException e) { map.put("path", dirName + "/" + newName + "_temp");
} catch (IOException e) {
e.printStackTrace();
map.put("error", "文件上传失败:" + e.getMessage());
} catch (RuntimeException e) {
e.printStackTrace(); e.printStackTrace();
map.put("error", "上传过程发生运行时异常:" + e.getMessage());
} }
Map<String, Object> map = new HashMap<>();
map.put("path", dirName + "/" + newName + "_temp");
return map; return map;
} }

Loading…
Cancel
Save