/**
* 上傳頭像
*
* @throws IOException
* @throws IllegalStateException
*/
public String upload(MultipartFile file) throws IllegalStateException, IOException {
File dir = new File(rootpath);
if (!dir.exists()) {
dir.mkdirs();
}
//讀取文件名
String fileName = file.getOriginalFilename();
if (!StringUtil.isEmpty(fileName)) {
//獲取文件的後綴
String suffix = FilenameUtils.getExtension(fileName);
//UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法,生成唯一的標識
//修改後的文件名(帶後綴)
String newFileName = UUID.randomUUID().toString().toLowerCase() + "." + suffix;
//public File(File parent, String child)--->dir就是相當於這個文件的路徑(不包含這個文件的文件名),newFileName指的是文件名;
File targetFile = new File(dir, newFileName);
//將文件提交到目的地文件系統中
file.transferTo(targetFile);
System.out.println(newFileName + "mmm");
//圖片上傳以後,“\\”要變成“/”、而且前面的根路徑也不需要了;
String imgpath = targetFile.getPath().replace("\\", "/").replace(rootpath, "");
System.out.println(imgpath);
return imgpath;
} else {
return null;
}
}
簡易的springboot上傳頭像(圖片)代碼片段
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.