上传文件并存储至resource/images
目录下
package com.sdut.controller;
import com.sdut.utils.ResV;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
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.util.UUID;
/**
* @Projectname: Cloud
* @Filename: UploadController
* @Author: SpringForest
* @Data:2022/11/27 20:32
* @Description:
* 上传文件并存储至resource/images目录下
*/
@RestController
@RequestMapping("/file")
public class UploadController {
@RequestMapping("/upload")
@ResponseBody
public ResV upload(MultipartFile file, HttpServletRequest request) throws IOException {
if (file == null || file.isEmpty()) {
return ResV.error("您传了个寂寞");
}
//重命名文件
String originalFileName = file.getOriginalFilename();
assert originalFileName != null;
String ext = "." + originalFileName.split("\\.")[1];
String uuid = UUID.randomUUID().toString().replace("-", "");
String fileName = uuid + ext;
//存储图片至resource/images文件夹下
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//指定文件存储路径
String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "/src/main/resources/images/";
String path = pre + fileName;
System.out.println(path);
try {
file.transferTo(new File(path));
} catch (Exception e) {
e.printStackTrace();
return ResV.error(e.toString());
}
return ResV.ok();
}
}