上传图片

   uploadImg (file) { // 上传图片 拿到上传文件,调接口,接口返回图片url,name等信息。
    // (这里注意content-type在上传文件或者图片的时为mutipart/form-data类型,headers可携带token等信息)
    // post 方法 content-type 为apllication/x-www-form-urcoded let param = new FormData() param.append('accountToken', this.$localStorageUtil.getHrAccountInfo().accountToken) param.append('file', this.uploadData.file, this.uploadData.file.name) this.$axios( { method: 'post', headers: { hrToken: this.$localStorageUtil.getHrAccountInfo().accountToken }, url: motivationApi.uploadNoticeImg, data: param } ).then((res) => { if (res.data && (res.data.return_code === '00')) { this.uploadData.url = res.data.data.fileUrl this.formValidate.coverImage = res.data.data.fileUrl this.uploadData.fileName = res.data.data.fileName } else { this.$Message.warning(res.data.return_msg) } }).catch(error => { console.log(error) }) }, handleBeforeUpload (file) { // let imgFormatArr = ['jpg', 'jpeg', 'png', 'gif'] let type = file.type.split('/') let size = file.size / 1024 / 1024 // M // 上传图片大小 if (type && type[0] === 'image' && imgFormatArr.includes(type[1]) && size <= 2) { // 上传图片格式和大小限制 this.uploadData.url = window.URL.createObjectURL(file) // https://test-api.fafuli.com/ 这里通过浏览器创建了一个以blob://开头的的本地图片链接 document.getElementById('uploadCoverImg').style.backgroundImage = "url('" + this.uploadData.url + "')"
        //上一行代码意思是 拿到本地图片链接,给id为uploadcoverimg的div设置背景图片样式 this.formValidate.coverImage = this.uploadData.url // 校验内容 this.uploadData.file = file this.uploadImg(file) return false // 最后return false 跳出 } else { this.$Message.warning('上传图片格式有误!') } }

  

posted @ 2021-12-06 13:45  everseven  阅读(18)  评论(0)    收藏  举报