An example of vue uploading pictures using native components
- 2021-08-16 22:51:59
- OfStack
Requirements Description: It is necessary to assign the picture path returned from the background to src of img
Upload 1 picture on 1 page
When there is only one place on a page to upload pictures, it is very simple to bind the upload button directly
html page
<div class="col-md-4">
<input class="hidden" accept="image/png,image/jpg" type="file" id="tempUploadFile" v-on:change="uploadPic($event)" />
<input class="hidden" v-model="mapItem.MapIcon" />
<img class="imgbgbox" v-bind:src="mapItem.MapIcon" />
</div>
js code: encapsulate the method of uploading pictures
uploadPic(e) {
var _self = this;
var inputFile = e.target;
if (!inputFile.files || inputFile.files.length <= 0) {
return;
}
var file = inputFile.files[0];
var formData = new FormData();
formData.append('file', file);
formData.append('SaveDir', 'Map/MapItem');
formData.append("FileName", $.whiskey.tools.dateFormat(new Date(), "HHmmssffff"));
$.ajax({
url: "/Upload/UploadPic",// Method of uploading pictures on the background
type: 'POST',
dateType: 'json',
cache: false,
data: formData,
processData: false,
contentType: false,
success: function (res) {
if (res.ResultType == 3) {
var filePath = res.Data.file;// Picture path returned from the background
_self.mapItem.MapIcon = filePath;// Assign a path to a declared variable
}
}
});
},
Upload multiple pictures on 2 1 pages
When a page has multiple positions need to upload pictures, if according to the above method, need to bind multiple upload functions, so I encapsulate the repeated parts, using promise function
html page
<div class="col-md-4">
<input class="hidden" accept="image/png,image/jpg" type="file" id="tempUploadFile" v-on:change="uploadPic($event)" />
<input class="hidden" v-model="mapItem.MapIcon" />
<img class="imgbgbox" v-bind:src="mapItem.MapIcon" />
</div>
js code: Method of encapsulating uploaded pictures
uploadPic(e) {
var _self = this;
var inputfile = e.target;
_self.uploadImg(inputfile).then(data => {
_self.mapItem.MapIcon = data;//data For the path of the fetched picture
})
},
// Encapsulated function
uploadImg(inputFile) {
var _self = this;
if (!inputFile.files || inputFile.files.length <= 0) {
return;
}
return new Promise((suc,err)=>{
var file = inputFile.files[0];
var filepath = "";
var formData = new FormData();
formData.append('file', file);
formData.append('SaveDir', 'Map/MapSite');
formData.append("FileName", $.whiskey.tools.dateFormat(new Date(), "HHmmssffff"));
$.ajax({
url: "/Upload/UploadPic",
type: 'POST',
dateType: 'json',
cache: false,
data: formData,
processData: false,
async:false,
contentType: false,
success: function (res) {
if (res.ResultType == 3) {
filepath = res.Data.file;
suc(filepath);
}
}
});
})
},
},
Additional knowledge: vue uses native input to upload pictures, preview and delete them
Look at the code ~
<template>
<div class="com-upload-img">
<div class="img_group">
<div v-if="allowAddImg" class="img_box">
<input type="file" accept="image/*" multiple="multiple" @change="changeImg($event)">
<div class="filter" />
</div>
<div v-for="(item,index) in imgArr" :key="index" class="img_box">
<div class="img_show_box">
<img :src="item" alt="">
<i class="img_delete" @click="deleteImg(index)" />
<!-- <i class="img_delete" @click="imgArr.splice(index,1)"></i> -->
</div>
</div>
</div>
</div>
</template>
js Part
<script>
export default {
name: 'ComUpLoad',
data() {
return {
imgData: '',
imgArr: [],
imgSrc: '',
allowAddImg: true
}
},
methods: {
changeImg: function(e) {
var _this = this
var imgLimit = 1024
var files = e.target.files
var image = new Image()
if (files.length > 0) {
var dd = 0
var timer = setInterval(function() {
if (files.item(dd).type !== 'image/png' && files.item(dd).type !== 'image/jpeg' && files.item(dd).type !== 'image/gif') {
return false
}
if (files.item(dd).size > imgLimit * 102400) {
// to do sth
} else {
image.src = window.URL.createObjectURL(files.item(dd))
image.onload = function() {
// Default scaled compression
var w = image.width
var h = image.height
var scale = w / h
w = 200
h = w / scale
// The default picture quality is 0.7 , quality The smaller the value, the more blurred the image is drawn
var quality = 0.7
// Generate canvas
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
// Create an attribute node
var anw = document.createAttribute('width')
anw.nodeValue = w
var anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(image, 0, 0, w, h)
var ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()// Picture format
var base64 = canvas.toDataURL('image/' + ext, quality)
// Callback function returns base64 Value of
if (_this.imgArr.length <= 4) {
_this.imgArr.unshift('')
_this.imgArr.splice(0, 1, base64)// The method to replace array data cannot be used here: this.imgArr[index] = url;
if (_this.imgArr.length >= 5) {
_this.allowAddImg = false
}
}
}
}
if (dd < files.length - 1) {
dd++
} else {
clearInterval(timer)
}
}, 1000)
}
},
deleteImg: function(index) {
this.imgArr.splice(index, 1)
if (this.imgArr.length < 5) {
this.allowAddImg = true
}
}
}
}
</script>