Gov*_*ari 10 multipartform-data react-native axios react-native-android react-native-image-picker
我正在向服务器发出 POST 请求以上传图像并在 react-native 中使用 axios 发送表单数据。我收到“网络错误”。我也尝试 fetch 但没有任何效果。使用 react native image picker libeary 选择 image.in postman api 工作正常
formData.append('title', Title);
formData.append('class_id', selectClass._id)
formData.append('subject_id', checkSelected)
formData.append('teacher_id', userId)
formData.append('description', lecture);
formData.append('type', 'image');
var arr=[];
arr.push(imageSource)
arr.map((file,index)=>{
formData.append('file',{
uri:file.path,
type:file.type,
name:file.name
})
})
axios({
method: 'post',
url: URL + 'admin/assignment/create',
data: data,
headers: {
"content-type": "multipart/form-data",
'x-auth-token': token,
},
})
.then(function (response) {
//handle success
console.log('axios assigment post',response);
})
.catch(function (response) {
//handle error
console.log('axios assigment post',response);
});
Run Code Online (Sandbox Code Playgroud)
小智 17
我面临的问题与您提到的问题很接近,是我在使用图像选择器并尝试使用 axios 上传文件时遇到 NetworkError 。它在 iOS 中完美运行,但在 Android 中却无法运行。
\n这就是我解决问题的方法。
\n这里有两个独立的问题在起作用。让\xe2\x80\x99s 说我们从图像选择器获取imageUri,然后我们将使用以下代码行从前端上传。
\nconst formData = new FormData();\nformData.append(\'image\', {\n uri : imageUri,\n type: "image",\n name: imageUri.split("/").pop()\n});\nRun Code Online (Sandbox Code Playgroud)\n第一个问题与 imageUri 本身有关。如果让\xe2\x80\x99s 说照片路径是/user/.../path/to/file.jpg。然后,Android 中的文件选择器会将 imageUri 值指定为 file:/user/.../path/to/file.jpg,而 iOS 中的文件选择器会将 imageUri 值指定为 file:///user/.../path/to /文件.jpg。
\n第一个问题的解决方案是在android中的formData中使用file://而不是file:。
\n第二个问题是我们没有使用正确的哑剧类型。它在 iOS 上运行良好,但在 Android 上则不行。更糟糕的是文件选择器包给出的文件类型为 \xe2\x80\x9cimage\xe2\x80\x9d 并且它没有给出正确的 mime 类型。
\n解决方案是在字段类型的 formData 中使用正确的 mime-type。例如:.jpg 文件的 mime 类型为 image/jpeg,.png 文件的 mime 类型为 image/png。我们不必手动执行此操作。相反,您可以使用一个非常著名的 npm 包,称为mime。
\n最终的工作解决方案是:
\nimport mime from "mime";\n\nconst newImageUri = "file:///" + imageUri.split("file:/").join("");\n\nconst formData = new FormData();\nformData.append(\'image\', {\n uri : newImageUri,\n type: mime.getType(newImageUri),\n name: newImageUri.split("/").pop()\n});\nRun Code Online (Sandbox Code Playgroud)\n我希望这有助于解决您的问题:)
\n反应本机解决方案
如果您使用Axios或Fetch在上传文件或数据时React Native得到了。Network Error
尝试commenting从以下行/android/app/src/main/java/com/{your_project}/MainApplication.java
它位于该40-50线周围
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
Run Code Online (Sandbox Code Playgroud)
https://github.com/facebook/react-native/issues/28551
小智 6
我遇到了同样的问题。以下步骤对我有用。
formData代码如下:let formData = new FormData();
let file = {
uri: brand.uri,
type: 'multipart/form-data',
name: brand.uri
};
formdata.append('logo', file);
Run Code Online (Sandbox Code Playgroud)
类型必须是“multipart/form-data”作为帖子标题。
“react-native”:“0.62.1”,“react”:“16.11.0”,“axios”:“^0.19.2”,
奇怪的解决方案我必须删除 android ->app->source->debug 中的 debug 文件夹
并再次重新启动应用程序,它解决了我的问题。我认为这是缓存问题。
| 归档时间: |
|
| 查看次数: |
7905 次 |
| 最近记录: |