Article directory
-
- summary
- Instructions
- custom upload
Summary
element ui file or image upload
How to use
Introduce elementui Use element ui to upload file components The following is a picture as an example
<el-form-item label="Photo:"> <el-upload ref="upload" class="upload-demo upload_bg" :action="uploadImg" :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview" :before-upload="handleBefore" :on-remove="handleRemove" :on-change="handleImgChange" :file-list="imgList" list-type="picture-card" multiple :limit="6" :on-exceed="handleExceed" :auto-upload="false" > <i slot="default" class="el-icon-plus"></i> <div slot="tip" class="el-upload__tip"> Upload pictures, the size should not exceed 4M. </div> </el-upload> </el-form-item>
:action="uploadImg" uploading : upload image URL For example: 'http://xx.xxx.xxx.xxx:xxxx/api/fileUpLoad/images
:before-upload Intercept before image upload
// Intercept before image upload handleBefore(file) {<!-- --> if (file. size >= 4000000) {<!-- --> this.$baseMessage('The picture is too large, please do not exceed 4M', 'error') return false } }, // callback when the file state changes handleImgChange(file, fileList) {<!-- --> if (file.status === 'ready') {<!-- --> this.readyState++ } else {<!-- --> this.readyState-- } }, // Callback after the image is uploaded successfully handleAvatarSuccess(response, file, fileList) {<!-- --> let that = this this.num += 1 let obj = {<!-- --> code: '', id: 0, url: '', fileName: '', shortUrl: '', } obj.url = file.response.response[0] obj.shortUrl = file.response.response[0] obj.fileName = file.name that.form.accidentFiles.push(obj) if (that.num === that.readyState) {<!-- --> // submit data if (that.form.id) {<!-- --> that._doEdit(that.form.id) } else {<!-- --> that._doCreate() } } }, // delete uploaded photo handleRemove(file, imgList) {<!-- --> if (file.status === 'success') {<!-- --> let len = this.form.accidentFiles.length let dels = -1 for (let i = 0; i < len; i ++ ) {<!-- --> if (this. form. accidentFiles[i]. id === file. id) {<!-- --> dels = i } } if (dels !== -1) {<!-- --> this.form.accidentFiles.splice(dels, 1) } } else if (file. status === 'ready') {<!-- --> this.readyState-- } }, // image zoom preview handlePictureCardPreview(file) {<!-- --> this.dialogImageUrl = file.url this.dialogVisible = true }, // upload more than 6 files handleExceed(files, fileList) {<!-- --> this.$message.warning( `The current limit is to select 6 files, this time ${<!-- -->files.length} files are selected, and a total of ${<!-- --> is selected files.length + fileList.length } files` ) },
Custom upload
<el-upload ref="upload" action="uploadImg" accept=".txt, .txts, .pdf, .docx,.xlsx, .xls, .jpg, .jpeg, .png" :on-remove="handleRemove" :on-change="handleImgChange" :file-list="imgList" :on-preview="handlePreview" :http-request="handUploadFile" :before-upload="handleBefore" :limit="6" multiple :on-exceed="handleExceed" :auto-upload="false" > <el-button size="small" type="primary">Click to upload</el-button> <div slot="tip" class="el-upload__tip"> <!-- Upload attachments, the size does not exceed 4M. --> </div> </el-upload>
// callback when the file status changes handleImgChange(file, fileList) {<!-- --> if (file.status === 'ready') {<!-- --> this.readyState++ } // else {<!-- --> // this. readyState-- // } }, // // Intercept before image upload handleBefore(file) {<!-- --> let objs = {<!-- --> fileName: changeTimes(new Date()) + '-' + file.name, } return new Promise((resolve, reject) => {<!-- --> getFileUrl(objs).then(({<!-- --> response }) => {<!-- --> this.uploadImg = response //Adjust the background interface to obtain the file upload path resolve(response) }) }) // if (file. size >= 4000000) {<!-- --> // this.$baseMessage('The attachment is too large, please do not exceed 4M', 'error') // return false // } }, handUploadFile(res) {<!-- --> let shortUrl = changeTimes(new Date()) + '-' + res.file.name let fileName = res.file.name let uploadImg = this.uploadImg this.num += 1 FileConvertBase(res.file) .then((res) => {<!-- --> uploadRequest(uploadImg, 'put', dataURItoBlob(res)) //In this case only the put method can be used .then((res) => {<!-- --> this.readyState-- let obj = {<!-- --> code: '', id: 0, fileName: fileName, shortUrl: shortUrl, } this.form.contractFiles.push(obj) if (this.readyState === 0) {<!-- --> // submit data if (this. form. id) {<!-- --> this._doEdit(this.form.id) } else {<!-- --> this._doCreate() } } }) .catch((res) => {<!-- --> this. Loading. close() }) }) .catch((res) => {<!-- --> this. Loading. close() }) }, // delete handleRemove(file, imgList) {<!-- --> if (file.status === 'success') {<!-- --> let len = this.form.contractFiles.length let dels = -1 for (let i = 0; i < len; i ++ ) {<!-- --> if (this. form. contractFiles[i]. id === file. id) {<!-- --> dels = i } } if (dels !== -1) {<!-- --> this.form.contractFiles.splice(dels, 1) } } else if (file. status === 'ready') {<!-- --> this.readyState-- } }, // upload more than 6 files handleExceed(files, fileList) {<!-- --> this.$message.warning( `The current limit is to select 6 files, this time ${<!-- -->files.length} files are selected, and a total of ${<!-- --> is selected files.length + fileList.length } files` ) },
Encapsulation request interface
import axios from 'axios' import {<!-- --> baseURL, // requestTimeout, } from '@/config' const instance = axios.create({<!-- --> baseURL, // timeout: requestTimeout, headers: {<!-- --> 'Content-type': 'multipart/form-data', }, }) export default function (url, method, data) {<!-- --> return new Promise((resolve, reject) => {<!-- --> instance({<!-- --> url, method, data }).then(res => {<!-- --> resolve(res) }) }) }
Upload file format conversion
// convert the file file to base64, and get the image in base64 format function FileConvertBase(file) {<!-- --> if (!file) return return new Promise((resolve, reject) => {<!-- --> try {<!-- --> var reader = new FileReader() reader. readAsDataURL(file) reader.onload = function () {<!-- --> resolve(reader. result) }; } catch (err) {<!-- --> console. log(err); reject(err) } }) } // convert base64 to blob stream function dataURItoBlob(base64Data) {<!-- --> //console.log(base64Data);//data:image/png;base64, var byteString if (base64Data.split(',')[0].indexOf('base64') >= 0) byteString = atob(base64Data.split(',')[1]) //base64 decoding else {<!-- --> byteString = unescape(base64Data. split(',')[1]) } var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0] //mime type -- image/png // var arrayBuffer = new ArrayBuffer(byteString.length); // Create a buffer array // var ia = new Uint8Array(arrayBuffer);//Create view var ia = new Uint8Array(byteString.length) // create a view for (var i = 0; i < byteString. length; i ++ ) {<!-- --> ia[i] = byteString. charCodeAt(i) } var blob = new Blob([ia], {<!-- --> type: mimeString, }) return blob } export {<!-- --> FileConvertBase, dataURItoBlob }