使用ElementUi中的Upload 上傳遇到的坑點
1、我使用的Ui樣式是這個樣式,為手動上傳形式

2、話不多說,上代碼
<el-upload
v-model="ruleUserForm.logoUrl"
class="upload-demo"
ref="upload"
action="aaa"
:on-preview="handlePreview"
:on-remove="handleRemove"
:http-request="uploadFile"
:auto-upload="false"
:limit="1"
list-type="picture"
style="width:300px"
>
<el-button slot="trigger" size="small" type="primary"
>選取檔案</el-button
>
<el-button
style="margin-left: 10px"
size="small"
type="success"
@click="submitUpload"
>保存</el-button
>
</el-upload>
3、遇到問題–跨域問題
點擊保存按鈕出現下面報錯:

解決辦法:使用vue.config.js代理
module.exports = {
devServer: {
port: port,
https: false, // https:{type:Boolean}
open: true, //配置自動啟動瀏覽器
proxy: {
'/file': {
target: "http://192.168.0.250:6002",
pathRewrite: {
'^/file': ''
},
changeOrigin: true
}
},
},
},
重點來了,當我配置完后,再去點擊保存,發現跨域問題并沒有解決,驚了個大呆,除錯了半天,最終發現,是因為我VSCode設定了自動保存,配置完后,忘記重啟vue專案!!!此處強調三遍,修改完config.js后一定要重啟專案!修改完config.js后一點要重啟專案!修改完config.js后一點要重啟專案!
4、圖片上傳介面寫法
還是跟之前一樣,只是加上你剛剛配置的名字而已
// 圖片上傳介面
export const userUploadFile = (parms) => {
return http.post('/file/cron/files/uploadFile',parms)
}
5、關于action的坑點
因為我是手動上傳,所以action隨便寫什么都可以(我不是很推薦在action直接寫請求地址,之前遇到的跨問題域,就是直接在action里寫請求地址導致的- - -僅代表個人觀點)
6、Base64的設定,見代碼
getBase64(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function () {
imgResult = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(imgResult);
};
});
},
7、http-request的使用
根據ElementUi的官方檔案解釋為:覆寫默認的上傳行為,可以自定義上傳的實作 ElementUi
官網
所以,直接在http-request對應的函式里面寫入我們的圖片上傳函式
async uploadFile(params) {
const _file = params.file;
let photoBase64 = await this.getBase64(_file);
//此處可以定義上傳檔案大小等
// const isLt2M = _file.size / 1024 / 1024 < 2;
// // 通過 FormData 物件上傳檔案
// var formData = new FormData();
// formData.append("file", _file);
// if (!isLt2M) {
// this.$message.error("請上傳2M以下的.xlsx檔案");
// return false;
// }
var arr = [];
arr.push(photoBase64);
var pas = {
type: 1,
base64: arr,
};
userUploadFile(pas).then((res) => {
if (res.data.code == 1000) {
this.ruleUserForm.logoUrl=res.data.data[0];
this.$message({
message: '圖片上傳成功',
type: "success",
});
} else {
this.$message({
message: res.data.msg,
type: "error",
});
}
});
},
此處使用async和await的原因:
由于在設定圖片Base64的時候,使用了一個promise方法,它為異步函式,如果不等待他回傳,就拿到的是一個promise物件,這不是我們要的具體的值
8、按鈕設定的函式去觸發該方法
submitUpload() {
this.$refs.upload.submit();
//觸發uploadFile函式
},
9、檔案上傳鉤子和移除鉤子,我沒有特殊用法,直接復制官網例子,這里就不做贅述,代碼如下
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/237664.html
標籤:其他
