1.
2.
<el-upload
style="display: flex; flex-direction: row"
class="avatar-uploader"
name="upfile"
action="#"
:accept="accept"
:show-file-list="false"
ref="upload"
auto-upload
:on-success="uploadSuccess"
:http-request="(params) =>
httpUploadFile(params, index)" >
<div>
<img v-if="logoImage" :src="logoImage" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</div>
</el-upload>
3.上传对象的方法
定义数据:
data(){
return:{
logoImage: '',
accept: '.jpg,.jpeg,.png,.JPG,.JPEG',
}
},
//上传图片
httpUploadFile(param, index) {
console.log('进入uploadFile');
let that = this;
let url = api.fileUploadUrl;
const imgObj = new Image();
imgObj.src = URL.createObjectURL(param.file);
imgObj.setAttribute('crossOrigin', 'Anonymous');
let fileId = '';
if (that.value && that.value != '') {
fileId = that.value;
} else {
//没有fileid的前端生成
fileId = that.setNewValue();
}
var formData = new FormData();
formData.append('file', param.file);
formData.append('fileid', fileId);
formData.append('__sid', localStorage.getItem('sessionId'));
formData.append('height', imgObj.height || 110);
formData.append('width', imgObj.width || 110);
let size = parseFloat(param.file.size / 1024 / 1024);
if (size > 10) {
that.$message.warning('文件过大,无法上传');
return;
}
uploadFile(url, formData)
.then((res) => {
console.log('附件上传返回', res);
let body = res.body;
that.value = body.fileId;
body.name = body.fileOldName;
body.url = api.severUrl + body.imgUrl;
body.path = api.severUrl + body.imgUrl;
body.uid = param.file.uid;
// that.paramObj.fileId = body.fileId;
// that.fileLists.push(body);
this.logoImage = body.url;
// console.log(this.$refs.upload[index])
// this.$refs.upload[index].clearFiles();
})
.catch((err) => {
//异常报错
console.log(err);
that.$message.warning('上传失败,请稍后再试');
});
},
3.
setNewValue() {
var date = new Date();
var timeStr = date.getFullYear() + '';
timeStr = timeStr.substring(2);
if (date.getMonth() < 9) {
// 月份从0开始的
timeStr += '0';
}
timeStr += date.getMonth() + 1;
timeStr += date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
timeStr += '';
timeStr += date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
timeStr += '';
timeStr += date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
timeStr += '';
timeStr += date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
let cur = '';
for (let i = 0; i <= 5; i++) {
cur += '' + Math.floor(Math.random() * 10);
}
timeStr = timeStr + cur;
return timeStr;
},