最近正好學到了Element Ui的文件上傳組件,雖然不太難但一個人琢磨還是整了很久
以下是我整理的規(guī)范性文件上傳組件為例
文件上傳組件
前端
<!--action:設(shè)置文件上傳路徑
? ? limit:設(shè)置圖片上傳的最大數(shù)量
name:設(shè)置文件上傳的參數(shù)名稱
handleRemove:圖片上的刪除按鈕調(diào)用的方法
-->
<el-upload
? ? ? ?action="/upload"
? ? ? ?limit="1"
? ? ? ?name="picFile"
? ? ? ?list-type="picture-card"
? ? ? ?:on-preview="handlePictureCardPreview"
? ? ? ?:on-remove="handleRemove">
? ? <i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
? ? <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<el-button type="success">上傳圖片</el-button>
后端
此處的String dirPath = "D:/files"可以選取你電腦上的指定位置
@RequestMapping("/upload")
public String upload(MultipartFile picFile){// 參數(shù)名需要與組件中制定的name屬性名一致
? ?String fileName = picFile.getOriginalFilename();// 得到文件的初始文件全名
? ?System.out.println(fileName);
? ?// 文件數(shù)據(jù)需要存儲到數(shù)據(jù)庫服務(wù)器磁盤中
? ?// 如果使用文件全名容易出現(xiàn)文件重名覆蓋問題
? ?// 使用UUID.randomUUID生成唯一的16進制唯一標識符可避免這中問題
? ?String suffix = fileName.substring(fileName.lastIndexOf("."));// 截取后綴名
? ?fileName = UUID.randomUUID()+suffix;
? ?System.out.println(fileName);
? ?// 此時生成的文件名是唯一的
? ?// 如果網(wǎng)站傳輸數(shù)據(jù)量過大,將上傳的文件都存到一個文件夾中會使文件夾中的文件太多
// 此時最好給文件做一個分流處理
// 計劃以當前上傳事件為節(jié)點生成不同的文件目錄達到此效果
String dirPath = "D:/files";// 指定存儲位置
// 準備日期路徑: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /2023/03/07/文件名
SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
String datePath = format.format(new Date());// 得到當前系統(tǒng)使時間
File dirFile = new File(dirPath+datePath);
if(!dirFile.exists()){
? ?dirFile.mkdirs();//如果當前日期的文件夾不存在就創(chuàng)建一個
}
System.out.println(dirFile.getPath());// 文件路徑為D:\files\2023\03\07
String filePath = dirPath+datePath+fileName;// 圖片地址的全名
picFile.transferTo(new File(filePath));
// 將文件的時間路徑+文件路徑響應(yīng)給客戶端,做其他操作
return datePath+fileName;
}
接上面文章來源:http://www.zghlxwxcb.cn/news/detail-547015.html
組件之文件刪除
// 此時發(fā)出刪除圖片的請求
handleRemove(file, fileList) {
// ? 組件中handleRemove中傳遞來的file參數(shù)有一個response方法,他是剛才上傳圖片時返回的時間路徑+文件路徑
// 調(diào)用file.response,以此路徑為參數(shù)傳遞到后端做刪除操作 ? ?
? ?console.log(file, fileList);
? ?axios.get("/remove?url="+file.response).then(function (){
? ? ? ?console.log("刪除完成!");
? })
}
@RequestMapping("/remove")
public void remove(String url){
? ?System.out.println("url = " + url);
? ?// 接收到的路徑與不變的文件路徑進行拼接獲得全路徑名做刪除操作
? ?File file = new File("D:/files" + url);
? ?file.delete();
}
如有錯誤,歡迎指出文章來源地址http://www.zghlxwxcb.cn/news/detail-547015.html
到了這里,關(guān)于Element Ui 之 文件上傳組件的使用 Upload的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!