如何格式化我的 formData 对象的结构以匹配后端的预期?
How can I format the structure of my formData object to match what the backend expects?
我正在使用 formData POST 我通过 ImagePicker 上传的图像。我发送的参数是这样的:
let formData = new FormData();
formData.append('image', { uri: localUri, name: filename, type });
formData.append('description', 'this is the decription');
return await fetch('https://prana-app.herokuapp.com/v1/visions/', {
method: 'POST',
body: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-User-Email': this.state.email,
'X-User-Token': this.state.accessToken
},
});
};
这似乎不起作用,因为我得到了一个非常通用的 NoMethodError (undefined method
build' for nil:NilClass):` error.
考虑到 image
参数是图像而 description
参数是字符串,我如何才能以正确的方式 POST 我的参数?
谢谢
使用 Formdata 时 Content-Type 必须不同。
example.js:
fileSend = () => {
const apiUrl = "http://00.000.00.000:0000/upload";
const uri = this.state.image;
const stringdata = {
username: this.state.name,
introduce: this.state.introducetext,
addresstext: this.state.addresstext
};
const uriParts = uri.split(".");
const fileType = uriParts[uriParts.length - 1];
const formData = new FormData();
formData.append("userfile", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
for (var k in stringdata) {
formData.append(k, stringdata[k]);
}
const options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
return fetch(apiUrl, options)
如上例所示,如果 Stringdata 不是一个,Content-Type
应该写入 multipart/form-data
并将其传递给 For ... in
。
我正在使用 formData POST 我通过 ImagePicker 上传的图像。我发送的参数是这样的:
let formData = new FormData();
formData.append('image', { uri: localUri, name: filename, type });
formData.append('description', 'this is the decription');
return await fetch('https://prana-app.herokuapp.com/v1/visions/', {
method: 'POST',
body: formData,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-User-Email': this.state.email,
'X-User-Token': this.state.accessToken
},
});
};
这似乎不起作用,因为我得到了一个非常通用的 NoMethodError (undefined method
build' for nil:NilClass):` error.
考虑到 image
参数是图像而 description
参数是字符串,我如何才能以正确的方式 POST 我的参数?
谢谢
使用 Formdata 时 Content-Type 必须不同。
example.js:
fileSend = () => {
const apiUrl = "http://00.000.00.000:0000/upload";
const uri = this.state.image;
const stringdata = {
username: this.state.name,
introduce: this.state.introducetext,
addresstext: this.state.addresstext
};
const uriParts = uri.split(".");
const fileType = uriParts[uriParts.length - 1];
const formData = new FormData();
formData.append("userfile", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
for (var k in stringdata) {
formData.append(k, stringdata[k]);
}
const options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
return fetch(apiUrl, options)
如上例所示,如果 Stringdata 不是一个,Content-Type
应该写入 multipart/form-data
并将其传递给 For ... in
。