所以我尝试通过 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 上的调用,您可以在其中看到它们的工作。
我做错了什么?
最佳答案
您的 postman 显示您正在使用表单数据上传图像,但在您的代码中,您只是在不发送任何表单数据的情况下进行 JSON post 调用。您需要创建一个新的 FormData
实例,并将数据附加到它。在您的情况下,您希望发送带有 key file
的 result.uri
,这可以使用 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
});
});
关于javascript - 如何通过使用 fetch API 响应 native 将图像发布到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68404262/