上传文件到项目本身static当中 而不是上传的文件服务器上。
这种一般是很少的,但是也不排除使用这个。
首先我们看一下controller 处理,这里是通过对象进行接收,MultipartFile 文件接收,当然这里对象也可以换成Map。这里就是上传的项目static/upload 下面。如下图
上代码
@ResponseBody
@PostMapping("/vehicles")
public Object insert(Vehicle vehicle, @RequestParam(value = "file", required = false) MultipartFile file) throws FileNotFoundException {
if (file != null && !file.isEmpty()) {
String toPath = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
String realPath = toPath.replace('/', '\\').substring(1, toPath.length());
vehicle.setAttach(FileUtils.TransTo(file, realPath));
}
return getResult(vehicleService.insert(vehicle));
}
上面的FileUtils.TransTo 运用到工具类 如下:
class FileUtils {
public static String TransTo(MultipartFile multipartFile, String toPath) {
if (multipartFile == null || multipartFile.isEmpty()) {
return "";
}
File file = new File(toPath);
if (!file.exists()) {
//不存在就创建一个路径
file.mkdirs();
}
String filename = multipartFile.getOriginalFilename();
//把文件名称设置成唯一值uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
//完成上传文件
try {
multipartFile.transferTo(new File(toPath, filename));
} catch (Exception e) {
return "";
}
String result = "../upload/" + filename;
return result;
}