[英]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.