vue+springBoot element-ui upload元件
阿新 • • 發佈:2018-11-02
之前看過有人用beforeUpload 上傳檔案,用action不行,因為專案是前後端分離的,無法攜帶token,我研究了下一最終除錯通了。
<el-upload drag multiple
name="multipartfiles" //後臺接收檔案流的引數名
ref="upload"
:limit="limit" //限制檔案數量
:action="imageAction" //上傳圖片的訪問的伺服器路徑
:data="uploadData" //需要攜帶的其他引數
:on-preview="handlePreview" //點選時觸發的事件
:on-remove="handleRemove" //點選移除檔案時觸發的事件
:file-list="fileList" //已上傳的檔案list
:beforeUpload="beforeAVatarUpload" //上傳之前觸發的事件,我在這裡做了上傳檔案的型別控制
:on-exceed = "onExceed" //和limit一起用 當檔案數量超出限制時觸發
:onError="uploadError" //上傳失敗時觸發
:onSuccess="uploadSuccess" //上傳成功時觸發
:auto-upload="true"> //是否自動上傳
<i class="el-icon-upload"></i>
<div class="el-upload__text">將圖片拖到此處,或<em>點選上傳</em></div>
<div class="el-upload__tip" slot="tip">只能上傳'jpg/png/jpeg/gif'</div>
</el-upload>
export default {
data () {
return {
imageAction: this.$http.adornUrl(`/file/file/save?token=${this.$cookie.get('token' )}`),//。。。我才剛知道token可以不放在header中,直接放在路徑後面也行
limit: 1,
fileList: [],
}
},
method: {
// 當設定了取消自動上傳的時候,呼叫此方法開始上傳
// submitUpload () {
// this.$refs.upload.submit()
// },
handleRemove (file, fileList) {
if (file.status === 'success') {
this.$http({
url: this.$http.adornUrl('/file/file/delete'),
method: 'post',
data: this.$http.adornData([file.uid], false)
}).then(({data}) => {
this.$message.success('刪除圖片成功!')
})
}
},
handlePreview (file) {
if (file.status === 'success') {
this.imageVisiable = true
this.$nextTick(() => {
this.$refs.showImage.init(file.url)
})
}
},
onExceed (files, fileList) {
this.$message.error('提示:只能上傳一張圖片!')
},
// 圖片上傳
beforeAVatarUpload (file) {
if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
this.$message.error('只支援jpg、png、gif格式的圖片!')
return false
}
},
uploadSuccess (response, file, fileList) {
this.fileIds = response.fileIds
console.log('上傳圖片成功')
},
uploadError (response, file, fileList) {
this.$message.error('上傳圖片失敗!')
},
}
/**
* 儲存
*/
@RequestMapping("/save")
public R save(@RequestParam("multipartfiles") MultipartFile[] multipartfiles,String productId) throws IOException {
//獲取專案編譯之後的檔案路徑,一般是“專案路徑/target/classes”
String Path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")+"static/swagger/")).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(Path.indexOf(":") != 1){
Path = File.separator + Path;
}
//遍歷檔案
if(multipartfiles != null && multipartfiles.length>0){
for(MultipartFile item : multipartfiles){
String fileName = item.getOriginalFilename();//獲取檔名
String filePath = Path + "uploadFiles/uploadFiles";//自定義上傳路徑
File file = new File(filePath,fileName);
if(!file.exists()){//判斷資料夾是否存在,如果不存在則建立
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}
item.transferTo(file);//上傳檔案
}
}
return R.ok();
}