[英]How can I POST an image to DB via react native with the fetch API?
所以我试图通过 React Native 和 fetch API 将图像发布到服务器。
fetch(`${API}/uploadAvatar`, {
method: "POST",
headers: {
Authorization: bearer,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
body: JSON.stringify({ file: result.uri }),
})
.then((response) => response.json())
.then((json) => {
console.log({ json });
// this console.log outputs:
// "The format of the file should be jpg, png, jpeg.",
})
.catch((err) => {
console.log({ err });
});
}
result
返回:
{
"cancelled": false,
"height": 1776,
"type": "image",
"uri": "file:///var/mobile/Containers/Data/Application/18F84F29-CB72-4615-A68F-A00422D9B119/Library/Caches/ExponentExperienceData/%2540heythere%252Fkeep-up/ImagePicker/959E8BDE-FCF4-40C6-AF18-8F9EA852760D.jpg",
"width": 1776,
}
这些是对 POSTMAN 的调用,您可以在其中看到它们的工作情况。
我究竟做错了什么?
您的邮递员显示您正在使用表单数据上传图像,但在您的代码中,您只是进行 JSON 发布调用而不发送任何表单数据。 您需要创建一个新的FormData
实例,并向其追加数据。 在您的情况下,您希望将result.uri
与密钥file
一起发送,这可以使用formData.append('file', result.uri)
。 然后你必须将 formData 实例作为你的正文发送(在你的情况下,方法为 POST)
let formData = new FormData();
formData.append('file', result.uri);
fetch("api/SampleData", {
body: formData,
method: "post"
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});
您可以通过创建文件路径、文件名和文件类型的 JSON 对象,并使用参数将该对象附加到 Form Data 实例中,在 Form Data 的帮助下将图像发布到服务器。 该文件的路径是特定于平台的,因此您必须为路径添加条件。 请参考代码片段。
let Data = new FormData();
Data.append('file',
{
uri: Platform.OS === 'android' ? result.uri: result.uri.replace('file://',''),
type: result.type,
name: result.uri.replace(/^.*[\\\/]/, '')
});
fetch("api/SampleData", {
body: Data,
method: "post",
headers: {'Content-Type': 'multipart/form-data'}
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.