vue代碼
<el-upload
ref="upload"
class="avatar-uploader define-uploader"
accept=".jpg, .jpeg, .png"
:file-list="fileList"
:auto-upload="false"
:show-file-list="false"
action
:http-request="carouselUpload"
:on-change="handleChange"
>
<img
v-if="imageUrl"
:src="imageUrl"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button plain @click="uploadFile()">手動上傳</el-button>
js代碼
<script>
export default{
data(){
fileList: [],
imageUrl:"",
},
methods:{
handleChange(file, fileList) {
var _this = this;
const isTypeTrue = /^image\/(jpeg|png|jpg)$/.test(file.raw.type);
const isLt300K = file.raw.size / 1024 < 300;
// _this.saveData.imageUrl ="";
if (!isLt300K) {
this.$message.error("上傳圖片大小不能超過300K!");
return;
}
if (!isTypeTrue) {
this.$message.error("上傳圖片格式不對!");
return;
}
new Promise(function(resolve, reject) {
//upload內部需要一個promise,簡單的return出false並沒有什麼用
let width = 714;
let height = 280;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function() {
let valid = img.width == width && img.height == height;
valid ? resolve() : reject();
};
img.src = _URL.createObjectURL(file.raw); //onload是異步加載
}).then(
() => {
_this.imageUrl = URL.createObjectURL(file.raw);
console.log("222");
return file.raw;
},
() => {
this.$message.error("上傳的圖片必須是714*280!");
return Promise.reject();
}
);
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]]; // 這一步,是 展示最後一次選擇的csv文件
}
},
carouselUpload(param) {
//此處寫手動上傳的方法,上傳的地址及方式;
},
//手動上傳
uploadFile(){
//這裏上傳的執行的就是carouselUpload() 方法;
this.$refs.upload.submit();
}
}
}
</script>