1、在Vue中使用multipart/form-data上传文件
<ul class="upload-imgs">
<li v-if="imgs.length < 9">
<input type="file" class="upload" @change="addImg" ref="inputer" multiple accept="image/png,image/jpeg,image/gif,image/jpg" />
<a class="add">
<Icon type="md-add" class="iconfont" />
</a>
</li>
<li v-for="(value, key) in imgs" :key="key">
<p class="img">
<img :src="value.url" />
</p>
</li>
</ul>
// 获取图片路径
getImageUrl(file) {
var url = null;
if (window.createObjcectURL !== undefined) {
url = window.createOjcectURL(file);
} else if (window.URL !== undefined) {
url = window.URL.createObjectURL(file);
} else if (window.webkitURL !== undefined) {
url = window.webkitURL.createObjectURL(file);
}
return url;
},
// 选择图片
addImg(e) {
const file = e.target.files[0];
let src = this.getImageUrl(file); //blob地址
let array = this.imgs;
let obj = {
file: file,
name: file.name,
url: src
}
array.push(obj);
this.imgs = array;
// var reader = new FileReader();
// reader.onload = (data) => {
// console.log(data.target.result) //base64
// };
// reader.readAsDataURL(file);
e.target.value = ""; // input连续上传同一张
},
// 提交
submitFeebackInfo() {
var formFile = new FormData();
formFile.append("content", this.problem);
formFile.append("order_no", this.number);
if (this.imgs.length) {
this.imgs.forEach(item => {
formFile.append('image[]', item.file)
})
}
this.$http.submitFeedback(formFile).then((res) => {
this.$message.success({
content: res.msg,
});
});
},
2、在uniapp中使用multipart/form-data上传文件
<view class="img_list">
<image src="../../static/img/repair_add.png" mode="" class="up_icon" @click="chooseImage"></image>
<view class="img_item" v-for="(item,index) in fileList" :key="index">
<image :src="item.uri" mode="" class="up_img"></image>
</view>
</view>
// 选择图片
chooseImage() {
uni.chooseImage({
count: 9-this.fileList.length,
success: res => {
let array = this.fileList;
let arr = res.tempFilePaths.map(item => {
let obj = {
uri: item,
name: 'images[]'
}
return obj;
})
let files = res.tempFiles;
for(let i = 0; i < arr.length; i++) {
arr[i].file = files[i];
}
this.fileList = [...arr, ...array];
}
});
},
// 提交
submit() {
let params: {
title: this.title,
content: this.content
}
let images = [];
if(this.fileList.length) {
images = this.fileList;
}
uni.uploadFile({
url: url,
files: images,
header: {
token: token
},
formData: params,
success: res => {
let response = JSON.parse(res.data);
if (response.code === 200) {
console.log(response.data)
} else {
uni.showToast({
title: response.msg,
position: "center",
icon: "none",
duration: 2000
})
}
},
fail: err => {
uni.showToast({
title: "文件上传失败",
position: "center",
icon: "none",
duration: 2000
})
}
})
}