vue 选择图片(限定大小)上传到服务器
FormData:
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
成果:
![](https://images2018.cnblogs.com/blog/1249405/201807/1249405-20180716150833281-695655636.png)
html:
<div class="pdt15 pdb15"> <div id="preview" class="preview" v-for="(Img, index) in files" :key="index"> <img src="./img/cross.png" alt="叉" class="delimg" @click="delimg(index)"> <img :src="Img.path" alt="" class="addimg"> </div> <label for="browse" class="browse"> <input class="hidden" id="browse" type="file" accept="image/*" @change="previewFiles($event)" multiple> <img src="./img/icon-photo.png" width="100" height="100" alt="照相机"> </label> </div>
js:
1 //上传图片
2 previewFiles(e){
3 let files = e.target.files
4 for (let i = 0; i < files.length; i++) {
5 if (files[i].size/1024/1024 > 2) { //限制每张上传图片的大小
6 alert('第'+(i+1)+'张图片大于2M,请上传小于2M的图片');
7 return;
8 }
9 }
10 // console.log(files[0].size/1024/1024);
11 let formData = new FormData();
12 formData.append("action","upresumefile");//调用它的append()
方法来添加字段
13 for (let i = 0; i < files.length; i++) {
14 formData.append("file[]",files[i]);
15 }
16 17 this.$http.post('/API/app/infointerface.ashx',formData)
18 .then((res) => {
19 if (res.data.Result) {
20 this.files = this.files.concat(res.data.Data); //把服务器返回的图片路径获取下来,在页面显示
21 // console.log(this.files);
22 }
23 })
24 },
25 //删除图片
26 delimg(ind){
27 this.files.splice(ind, 1);
28 },
FormData对象用以将数据编译成键值对,以便用XMLHttpRequest
来发送数据。其主要用于发送表单数据,但亦可用于发送带键数据(keyed data)
对于formData对象的简单常见用法推荐看:https://blog.csdn.net/zqian1994/article/details/79635413