Requirement description: Need to assign the image path returned from the background to the src of img
1 Upload a picture per page
When a page has only one location to upload pictures, it is very simple, directly bind the upload button
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",//后台上传图片的方法
type: 'POST',
dateType: 'json',
cache: false,
data: formData,
processData: false,
contentType: false,
success: function (res) {
if (res.ResultType == 3) {
var filePath = res.Data.file;//后台返回的图片路径
_self.mapItem.MapIcon = filePath;//将路径赋值到声明的变量中
}
}
});
},
2 Upload multiple pictures on one page
When a page has multiple locations that need to upload pictures, if you follow the above method, you need to bind multiple upload functions, so I encapsulated the repeated parts and used the 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: encapsulate the method of uploading pictures
uploadPic(e) {
var _self = this;
var inputfile = e.target;
_self.uploadImg(inputfile).then(data => {
_self.mapItem.MapIcon = data;//data为取到的图片路径
})
},
//封装函数
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);
}
}
});
})
},
},