工具类
package com.project.supplier.util;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
@Component
public class UploadUtil {
public static String upload(MultipartFile mf, String dirPath) {
//得到上传文件的名称
String fileName = mf.getOriginalFilename();
//文件重命名,防止同名
fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
try {
//得到上传文件存放目录的真实路径
URL url = Thread.currentThread().getContextClassLoader()
.getResources(dirPath).nextElement();
String filePath = URLDecoder.decode(url.getFile(), "utf-8");
//将上传文件的二进制数据写入指定的文件
mf.transferTo(new File(filePath+"/"+fileName));
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
Controller
package com.project.supplier.controller;
import com.project.common.result.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Controller
@Api("上传文件的控制器")
@ResponseResult
public class IndexController {
@ResponseBody
@PostMapping("/upload")
public Object upload(@RequestParam(value = "file", required = false) MultipartFile file){
String path = "d:/server/upload";
// 获取上传图片的文件名
String fileName = file.getOriginalFilename();
// 截取后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 生成新的文件名(时间 + 随机数 + 后缀名)
String newFileName = System.currentTimeMillis() + "_" + String.valueOf(Math.random()).substring(2) + suffixName;
File targetFile = new File(path, newFileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
return newFileName;
}
}