Getting error during uploading a video in react native - react-native

I am fetching video from mobile using react-native-image-picker and uploading it to the server by using the fetch method. Don't know what I am doing wrong?
constructor(props){
super(props);
this.state = {
isLoading:true,
isModalVisible: false,
isOptionVisible:false,
avatarSource:"",
chapname:'',
chapdesc:''
}
};
var formData = new FormData();
formData.append('name', 'video name');
formData.append('desc', 'video description');
formData.append('file', {uri: this.state.avatarSource, name: this.state.avtarname.fileName, type: 'video/mp4'});
fetch(api, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type' :'multipart/form-data',
'Authorization': `JWT ${teacher_token}`
},
body: formData
})
and here is the response when I pick a video from phone
{path: "/storage/emulated/0/DCIM/Camera/VID_20200306_172706.mp4", uri: "content://com.miui.gallery.open/raw/%2Fstorage%2Fe…ted%2F0%2FDCIM%2FCamera%2FVID_20200306_172706.mp4"}
the error I getting is a network request failed. Here is the error which gets on the console
Fetch Error TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (E:\eshikshaserver\node_modules\whatwg-fetch\dist\fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (E:\eshikshaserver\node_modules\event-target-shim\dist\event-target-shim.js:818)
at XMLHttpRequest.setReadyState (E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388)
at E:\eshikshaserver\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (E:\eshikshaserver\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436)
at E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111
at MessageQueue.__guard (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (E:\eshikshaserver\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110)
I know something I am missing but can not find it. Stucked on it.

Related

Network Error While making axios call with Form Data

We have an application where we need to upload documents or images:
react: 17.0.2
react-native: 0.68.2
axios: 1.3.2
While making web service call using axios, we are getting Network Error in both iOS and Android.
Same API is working in web and through Postman.
Code (Same code is working fine with Json data.)
try {
var formData = new FormData();
formData.append('file', fileUpload);
const obj = { hello: "world" };
formData.append('param', JSON.stringify(obj));
const response = await axios({
method: 'post',
url: 'https://xxxxxxxxxxx.com/fr_webservice/file/doUpload',
data: formData,
headers: {
'x-auth-token': authData.token,
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data"
},
});
console.log("[Form Data Response]: ", response);
} catch (error) {
console.log("[Form Data Error]: ", error);
}
"AxiosError: Network Error
at XMLHttpRequest.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:191293:16)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:26337:27)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25607:20)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25417:16)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25543:47
at EventEmitter.emit (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:1731:37)
at MessageQueue.__callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2533:31)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2302:17
at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2492:13)
at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2301:14)"

multipart/form-data request failing in react-native

I get the following error when I set the 'Content-Type' as 'multipart/form-data' in react-native.
Below is my code -
const formData = new FormData();
formData.append('org_id', org_id);
formData.append('ans', userAns);
formData.append('remark', userRemark);
formData.append('img', userImg);
files.forEach(file => {
formData.append('files', {
name: file.fileName,
type: file.type,
uri: file.uri,
});
});
const resp = await multiPartInstance({
method: 'PUT',
url: `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
data: formData,
});
return Promise.resolve(true);
I am using axios for calling apis. multiPartInstance is an axios instance -
const multiPartAccessToken = async (config: AxiosRequestConfig) => {
config.headers = {
Accept: 'application/json',
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data;',
};
config.timeout = 30000;
return config;
};
I've tried the above with fetch also but I keep getting the same error. The strangest part is that this request hits the server, server sends a response too but I get this error react-native side. I've noticed if I don't use FormData I don't get any error. But I need to use FormData as I have to upload image files.
Environment Details -
Windows version 21H2 (OS Build 22000.376)
react-native 0.66.3
react 17.0.2
axios ^0.24.0
react-native-image-picker ^4.3.0 (used for selecting images)
Flipper version 0.99.0
I've tried the solutions posted on below forums but they didn't work for me.
request formData to API, gets “Network Error” in axios while uploading image
https://github.com/facebook/react-native/issues/24039
https://github.com/facebook/react-native/issues/28551
I am as follow and works perfectly:
const oFormData = new FormData();
images.map((val, index) => {
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
});
return axios.post(postServiceUrl, oFormData);
Somehow react-native-blob-util doesn't give this error. I modified my code as below -
import ReactNativeBlobUtil from 'react-native-blob-util';
const fileData = files.map(file => {
return {
name: 'files',
data: String(file.base64),
filename: file.fileName,
};
});
try {
const resp = await ReactNativeBlobUtil.fetch(
'PUT',
`${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
{
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data',
},
[
...fileData,
// elements without property `filename` will be sent as plain text
{name: 'org_id', data: String(org_id)},
{name: 'ans', data: String(userAns)},
{name: 'remark', data: String(userRemark)},
{name: 'img', data: String(userImg)},
],
);

Android: Network Request Failed when trying to upload image with fetch

I'm trying to upload an image from storage to a restful API but I keep getting Network Request Failed on Android (which means the request doesn't even go through), haven't checked on iOS because I don't need that part yet. API is already working and has been tested with Postman.
The React Native code is:
body.append('vehicles',{
resource_id: 2,
resource: 'vehicles',
cat_file_id: fileId,
active: 1,
vehicles: photo, //<- photo value below
name: 'vehicles',
type: 'image/jpeg'
})
fetch(`${BASE_URL}/files`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Accept: "*/*",
Authorization: 'Bearer '+auth
},
body: body
}).then(response => response.json())
.then(response => {
console.log('IMAGE RESPONSE', response)
})
.catch(error => console.log('ERROR', error))
The photo value looks like file:///storage/emulated/0/DCIM/...
The response:
ERROR TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
at XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:436)
at MessageQueue.js:111
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:110)
On Postman the request looks something like this:
Already tried:
Removing Accept header
Changing Accept value to 'application/json'
Removing file:// from the image url
Added android:usesCleartextTraffic="true" to the manifest
Already checked:
No values are null or undefined
There is a working internet connection, all other network requests on the app are working fine
The Auth is correct
React Native version is 0.61.5
I found one missing line in your code let formData = new FormData();. but not sure is that the exact issue here.
By the way here is a sample working code from one of my project, and I customized it with your context.
Add your authentication
replace ImageURI with image path and URL_SAVE_IMAGE endpoint url
const newImage = {
resource_id: 2,
resource: 'vehicles',
cat_file_id: 1,
active: 1,
vehicles: ImageURI,
name: "my_photo.jpg",
type: "image/jpg",
};
let formData = new FormData();
formData.append("vehicles", newImage);
return fetch(URL_SAVE_IMAGE, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formData
}).then(response => response.json());
it should work!
What is your fetch(${BASE_URL}/files` backend server .. This usually happens when trying to connect to the backend api on the localhost machine.. Even if you use the IP address of the localhost, it still persists, so it is better to use online server for testing or just use ngrok(https://ngrok.com/) to serve your backend localhost via internet.
in gradle.properties change the flipper version to 0.47.0
try with Xhr, it's working as expected!
const URL = "ANY_SERVER/upload/image"
const xhr = new XMLHttpRequest();
xhr.open('POST', url); // the address really doesnt matter the error occures before the network request is even made.
const data = new FormData();
data.append('image', { uri: image.path, name: 'image.jpg', type: 'image/jpeg' });
xhr.send(data);
xhr.onreadystatechange = e => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('success', xhr.responseText);
} else {
console.log('error', xhr.responseText);
}
};
Nothing worked for me except using the Expo FileSystem uploadAsync
uploadImage = async ({ imageUri } }) => FileSystem.uploadAsync(
apiUrl,
imageUri,
{
headers: {
// Auth etc
},
uploadType: FileSystem.FileSystemUploadType.MULTIPART,
fieldName: 'files',
mimeType: 'image/png',
});
Note - imageUri in format of file:///mypath/to/image.png
Happy days!

React Native upload image to server failed in android

i am using the following code to but i keep getting in android, which was showing "Network request failed", but it was no problem if i not append photo file data in the FormData. Why I am getting this problem?
const data = new FormData();
data.append("name", "testName"); // you can append anyone.
data.append("photo", {
uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
type: 'image/png', // or photo.type
name: 'testPhotoName.png'
});
fetch('https://ptsv2.com/t/1gfl7-1544694996/post', {
method: "post",
body: data
}).then(res => {
console.log(res);
});

Network request failed while using Fetch in react-native

I am getting the following error when i try to fetch API from my local server
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:15823:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17900:39)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17655:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17482:16)
at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:17592:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:3478:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2384:44)
at blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2154:17
at MessageQueue.__guardSafe (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2346:11)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14) {stack: TypeError: Network request failed
at XMLHttpRe…081/9b6428f5-4e65-45a0-9490-3852c365f0df:2153:14),
message: Network request failed}
I am accessing the APi from my client as follows
const apiURL = "192.168.1.5:3000/api/";
fetch(apiURL + '/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.props.username,
password: this.props.password
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.log(error);
});
I am running the app on my actual device which runs in android 7.0.Both my laptop and mobile are connected on the same Wi-Fi. I check my manifest file and yes Internet permission was enabled. I am not sure what i am doing wrong.