我在 React Native 应用程序中使用 expo-camera 来拍摄图像,它以字符串形式返回图像位置。然后我获取这个字符串并尝试将其上传到 laravel php 后端:
const uploadImage = async (
imageUri: string,
protocolId: number,
name: string
) => {
const img = await fetch(imageUri);
const blob = await img.blob();
const file = new File([blob], imageUri);
const formData = new FormData();
formData.append("image", file);
formData.append("protocolId", protocolId.toString());
formData.append("name", name);
fetch(POST_UPLOAD_PROTOCOL_PHOTO, {
method: "POST",
headers: {
Authorization: `Bearer ${user?.token}`,
},
body: formData,
})
我在 iPhone 上测试了所有内容。我的后端收到了 protocolId 和 name 的值,但图像字段始终作为空文件发送。我尝试使用网络调试器拦截 api 调用,实际上该文件似乎是空的,因为请求的内容长度对于图像来说太小了。
我尝试从图像 uri 中删除“file://”,但这没有帮助。我尝试使用 Postman 进行 api 调用,并使用表单数据添加一个文件,效果非常好。我尝试了其他 stackoverflow 帖子中描述的解决方案,例如这个(在react-native中上传 blob/文件,内容为空),但我收到了一个错误
formData.append("img", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
因为 formData.append() 只接受字符串或 Blob
尝试使用我的功能
我对此函数做了什么更改,我更改了图像的有效负载(直接 URL 不起作用)
Content-Type
'multipart/form-data'
在标题中(没有 Content-Type 表单数据 api 将无法工作)
const uploadImage = async (
imageUri: string,
protocolId: number,
name: string
) => {
const formData = new FormData();
formData.append('name', name);
formData.append('protocolId', protocolId.toString());
formData.append('image', {
name: imageUri?.fileName, //file name here
size: imageUri?.fileSize, // optional
type: imageUri?.type, // file type here
uri: imageUri?.uri // file url here
});
let res = await fetch(
`${baseUrl}/fame/saveImage`,
{
method: 'post',
body: formData,
headers: {
Authorization: `Bearer ${user?.token}`,
'Content-Type': 'multipart/form-data',
},
}
);
let responseJson = await res.json();
if (responseJson.status == 1) {
alert('Upload Successful');
}
}