上传图片或文档 二进制文档流方式上传
问题: 接口上传图片 需要将图片以二进制得格式 与其他字段一块传给后端
方案: 改变接口传递类型 application/x-www-form-urlencoded
let params = {
thaliId: this.editData.thaliId,
thaliPrice: this.editData.thaliPrice,
salesInstructions: this.editData.salesInstructions,
imgFile: this.titleFile, //图片二进制格式
};
if (!this.titleFile) {
delete params.imgFile;
}
let data = this.stringify(params); //将参数转换成功 formdata 接收格式
payConfig
.updateOpThali(data, "application/x-www-form-urlencoded")
.then((res) => {
if (res.code != 0) {
this.$message.error(res.errorMsg);
this.loading = false;
return;
}
});
// 将参数转换成功 formdata 接收格式
stringify(data) {
const formData = new FormData();
for (const key in data) {
// eslint-disable-next-line no-prototype-builtins
if (data.hasOwnProperty(key)) {
if (data[key]) {
if (data[key].constructor === Array) {
if (data[key][0]) {
if (data[key][0].constructor === Object) {
formData.append(key, JSON.stringify(data[key]));
} else {
data[key].forEach((item, index) => {
formData.append(key + `[${index}]`, item);
});
}
} else {
formData.append(key + "[]", "");
}
} else if (data[key].constructor === Object) {
formData.append(key, JSON.stringify(data[key]));
} else {
formData.append(key, data[key]);
}
} else {
if (data[key] === 0) {
formData.append(key, 0);
} else if (data[key] === null) {
formData.append(key, null);
} else {
formData.append(key, "");
}
}
}
}
return formData;
},


浙公网安备 33010602011771号