[英]How can I POST an image to DB via react native with the fetch API?
So I am trying to POST an image to a server via React Native and 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
returns this: 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,
}
Those are the calls on POSTMAN where you can see they work.这些是对 POSTMAN 的调用,您可以在其中看到它们的工作情况。
What am I doing wrong?我究竟做错了什么?
Your postman shows that you're using form-data to upload the image, but in your code you're simply making a JSON post call without sending any form-data.您的邮递员显示您正在使用表单数据上传图像,但在您的代码中,您只是进行 JSON 发布调用而不发送任何表单数据。 You need to create a new
FormData
instance, and append data to it.您需要创建一个新的
FormData
实例,并向其追加数据。 In your case, you want to send the result.uri
with the key file
, this can be done using formData.append('file', result.uri)
.在您的情况下,您希望将
result.uri
与密钥file
一起发送,这可以使用formData.append('file', result.uri)
。 Then you gotta send the formData instance as your body (with method as POST, in your case)然后你必须将 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
});
});
You can post images to the server with the help of Form Data by creating a JSON object of the file path, file name, and file type and append the object into the Form Data instance with the parameter.您可以通过创建文件路径、文件名和文件类型的 JSON 对象,并使用参数将该对象附加到 Form Data 实例中,在 Form Data 的帮助下将图像发布到服务器。 The path of the file is Platform-specific therefore you have to add conditions for the path.
该文件的路径是特定于平台的,因此您必须为路径添加条件。 Please refer to the code snippet.
请参考代码片段。
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.