1.配置yml
file:
# 檔案路徑,使用jvm系統變量,相容windows和linux;
# profile: /img
profile: E:/img
2.配置通路路徑
@Configuration
public class UploadFilePathConfig implements WebMvcConfigurer {
@Value("${ruoyi.profile}")
public String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image
public static List<String> fileUploadImg(MultipartFile file) {
String customPath = sdf.format(new Date());
List<String> imgList = new ArrayList<String>();
if (file != null && !file.isEmpty()) {
// 擷取檔案名稱
String fileName = file.getOriginalFilename();
if (fileName != null && fileName != "") {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 擷取通路網址拼接檔案存放路徑
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/files/img/";
// 截取檔案名字尾
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
// 重命名
fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileF;
String fileMulu = uploadFolder + "/" + customPath;
Establish(fileMulu);
File file1 = new File(fileMulu);
// 儲存檔案
File targetFile = new File(file1, fileName);
try {
byte[] buffer = new byte[1024 * 1024];
InputStream is = file.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream os = new FileOutputStream(targetFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int bytesRead = 0;
while ((bytesRead = bis.read(buffer, 0, 1024 * 1024)) != -1) {
bos.write(buffer, 0, bytesRead);
bos.flush();
}
bos.close();
bis.close();
os.close();
is.close();
String msg = returnUrl + customPath + "/" + fileName;
imgList.add(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return imgList;
}
public static void Establish(String fileMulu) {
File file = new File(fileMulu);
if (!file.exists()){
file.mkdirs();
}
}
}