1. 前端传给后端进行上传
<el-image style="position:relative;height: 144px;width: 144px;border-radius: 50%"
:src="basicForm.avatarUrl"></el-image>
<label class="btn" for="fileUpload"
style="color: #f90;position: absolute;left: 25px;bottom: -50px;border: 1px solid #f90;font-size: 14px;height: 32px;width: 102px;text-align: center;line-height: 32px">更换头像<i
style="margin-left:5px"></i></label>
<input @change="picSubmit" type="file" accept="image/*" id="fileUpload"
style="position: absolute;clip: rect(0 0 0 0);"/>
picSubmit(event) { this.newFiles = event.target.files[0] || event.dataTransfer.files[0]; this.isChangePic = true; let reader = new FileReader(); var _this = this; reader.onload = (function () { return function (e) { _this.basicForm.avatarUrl = e.target.result; }; })(this.basicForm); reader.readAsDataURL(this.newFiles); },
提交:
import {Loading} from 'element-ui' // 等待样式
submitForm() {if (this.isChangePic) { // 上传头像接口 // let data = new FormData(); // data.append('docStream', this.newFiles); form的格式 let reader = new FileReader(); var _this = this; reader.onload = (function () { return function (e) { let options = { text: '正在修改信息', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)', color: '#f90' }; let loadingInstance = Loading.service(options); reApi.postAvatar(_this.newFiles.type.split('/')[1], e.target.result).then(res => { if (res.success) { _this.isChangePic = false; _this.basicForm.avatarUrl = res.data; }; })(this.newFiles); reader.readAsArrayBuffer(this.newFiles); } },
2. 前端上传OSS
picSubmit(event) { // console.log(event); let files = event.target.files || event.dataTransfer.files; if (!files.length) return; this.picValue = files[0]; onSetUpOSS(this.picValue, url => { this.productForm.picture = url; }); },
import OSS from 'ali-oss'; // 图片上传阿里云OSS function onSetUpOSS(image, callback = function () { }) { let client = new OSS({ region: 'oss-cn-shenzhen', accessKeyId: '', accessKeySecret: '', bucket: 'rootingfire-product' // 文件夹 }); client.put('目录' + new Date().getTime(), image).then((r1) => { callback(r1.url) }); } export default onSetUpOSS;