I am working with the above issue that has had me stymied for hours on Android. I am using:
XMLHTTPRequest to upload an image file to my server. I have verified using document explorer in android that the image actually exists at the given uri.
I get xhr object as:
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted":
false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept":
"application/json", "authorization": "Bearer **********", "content-type": "multipart/form-data", "x-tenant": "EOG"},
"_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_requestId": null, "_response": "Unrecognized FormData part.", "_responseType": "",
"_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url":
"*************/uploadFile", "readyState": 4, "responseHeaders": undefined, "status": 0,
"timeout": 0, "upload": {}, "withCredentials": true}
I noticed in the above object: "_response": "Unrecognized FormData part."
My code looks like:
const {pic, kyc_document, kyc_identifier, kyc_expiry_date, ssn} = data;
let xhr = new XMLHttpRequest();
xhr.open(
'POST',
'https://**********/upload',
true,
);
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.setRequestHeader('x-tenant', 'EOG');
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function (error) {
console.log(xhr);
console.log('ERROR -----------', error);
console.log(pic);
};
let formData = new FormData();
formData.append('kyc_type', 'identity');
formData.append('kyc_document', kyc_document);
formData.append('kyc_meta_data', {issuing_state: state});
formData.append('kyc_identifier', kyc_identifier);
formData.append('kyc_expiry_date', kyc_expiry_date);
formData.append('kyc_file', {
uri: pic.uri,
type: 'image/jpeg',
name: 'Id',
});
}
try {
xhr.send(formData);
} catch (e) {
console.log(e);
}
}
};
This is returning {"isTrusted": false}
The uri looks like "uri": "file:///data/user/0/com.mon.app/cache/Camera/e6c2ae90-a9a8-43aa-9e36-62c73a76f2ef.jpg"
my package details are:
"react": "16.11.0",
"react-native": "0.62.2",
Related
I am trying to open a server-sent-events connection on android in react native using XMLHttpRequest. My server does not see the attached authorization header. Any other headers that I attach to the request make it through. Here is my source code:
xhr = new XMLHttpRequest();
xhr.open("GET", "mydomain.com", true);
this._xhr.setRequestHeader("Accept", "text/event-stream");
this._xhr.setRequestHeader("Cache-Control", "no-cache");
this._xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
this._xhr.setRequestHeader("authorization", `Bearer: ${this.authorizationToken}`);
The value of the authorizationToken exists at runtime and is a normal jwt token. Using curl, I can successfully connect to my SSE server. However, it seems that the authorization token is stripped out of the request in react native. Is there a reason why this specific header is blocked? If I change the header key to authToken it is passed as expected. A hint may be related to this working on a localhost domain but not on production (real) domains. No fetch, no axios, I need to use XMLHttpRequest so I can establish a server-sent-events connection. Downstream shared code expects the presence of the authorization header. Here is what my server sees:
Request: {
url: '/testuser',
body: {},
params: {},
headers: {
host: 'mydomain.com',
deviceid: 'mydeviceid',
accept: 'text/event-stream',
'cache-control': 'no-cache',
'x-requested-with': 'XMLHttpRequest',
'accept-encoding': 'gzip',
'user-agent': 'okhttp/4.9.2',
'x-forwarded-for': '',
'x-forwarded-proto': 'https',
'x-envoy-external-address': '',
'x-request-id': '',
'x-envoy-attempt-count': '1',
'x-forwarded-client-cert': '',
'x-b3-spanid': '',
'x-b3-parentspanid': '',
'x-b3-sampled': '0'
}
}
Any help on this issue would be greatly appreciated.
Tried to make an XMLHttpRequest with an authorization header, and the header was stripped out before reaching the server.
tried this one and it's working fine. try to remove true from open method
const Http = new XMLHttpRequest();
Http.open("GET", url)
Http.setRequestHeader('authorization', `Bearer: ehwrwhrkjewhgrkjewhregwjwgrjwgrjerjeg`)
Http.send();
console.log("Http =>>>>", Http)
output:-
{
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": false,
"_headers": {
"authorization": "Bearer: ehwrwhrkjewhgrkjewhregwjwgrjwgrjerjeg"
},
"_incrementalEvents": true,
"_lowerCaseResponseHeaders": {},
"_method": "GET",
"_perfKey": "network_XMLHttpRequest_https://reqres.in/api/users?page=2",
"_performanceLogger": {
"_closed": false,
"_extras": {},
"_pointExtras": {},
"_points": {
"initializeCore_end": 8665333.465721,
"initializeCore_start": 8665252.249148
},
"_timespans": {
"network_XMLHttpRequest_http://localhost:8081/symbolicate": [Object],
"network_XMLHttpRequest_https://reqres.in/api/users?page=2": [Object]
}
},
"_requestId": null,
"_response": "",
"_responseType": "",
"_sent": true,
"_subscriptions": [{
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}, {
"context": undefined,
"listener": [Function anonymous],
"remove": [Function remove]
}],
"_timedOut": false,
"_trackingName": "unknown",
"_url": "https://reqres.in/api/users?page=2",
"readyState": 1,
"responseHeaders": undefined,
"status": 0,
"timeout": 0,
"upload": {},
"withCredentials": true
}
hi I have one endpoint which is pass multipart formdata
URL : http://100.20.168.179/public/index.php/maintenances/create_ticket
Method: Post
Body request
const SelectData = {
"description": "Fff",
"room_id": "Ghh",
"maintenance_unique_id": "1662630778728",
"lang_flag": "en",
"asset_type": "2",
"longitude": "0.0",
"work_type": "69",
"user_id": "20",
"latitude": "0.0",
"area": "291",
"location": "22",
"urgency_level": "4",
"category_name": "",
"device_id": "2",
"captured_adress": "3377",
"reported_on": "2022-09-08 03:22:58",
"is_mediafile": "0"
}
My code as below
const form = new FormData();
const imageFileData = {
name: imageFilePath?.fileName,
type: `image/jpg`,
uri: imageFilePath?.uri,
};
form.append('webdata', JSON.stringify(SelectData));
if (imageFilePath?.uri || videoFilePath?.uri ) {
form.append('file_name', imageFileData );
}
else{
form.append('file_name', JSON.stringify(null));
}
addTicket(Config.BASE_URL + '/maintenances/create_ticket',form);
useAddTicket.ts
const useAddTicket = () => {
// const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const navigation = useNavigation();
const addTicket = async (url: string, data: any) => {
console.log('formDatain Hook', data);
console.log('url Hook', url);
console.log('internet', globals.GlobalVariable.isConnected);
if (globals.GlobalVariable.isConnected === true) {
try {
setIsLoading(true);
const headers = {
'Content-Type': 'multipart/form-data; boundary=V2ymHFg03ehbqgZCaKO6jy',
// Connection: 'keep-alive',
// 'Content-Disposition': 'form-data; name="webdata"',
};
const response = await axios.post(url, data, { headers: headers });
if (response.data.sStatus == 1) {
setIsLoading(false)
console.log('useAddTicket Data res -->', response);
Alert.alert(`${response.data.sData.maintenance_id}`, response.data.sMessage, [
{ text: 'OK', onPress: () => navigation.goBack() },
]);
}
} catch (error) {
console.log('useAddTicket error -->', error);
setIsLoading(false);
}
} else {
Alert.alert('No Internet!');
}
};
return {
isLoading,
// data,
addTicket,
};
};
export default useAddTicket;
Issue is Above code working in iOS emulator but in Android it is not working in emulator as well as Real device . When i try to run in android it is continuously loading API call is not happened so any idea how can I solve this ? Your all suggestions is appreciated
NOTE: I mage getting log till internet true inside addTicket function. It means my request is not reach to Endpoint
Try as below:
const oFormData = new FormData();
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
return axios.post(postUrl, oFormData);
I am trying to upload image to an API the iOS version is working good but there is problem in android, My code is bellow.
const uploadUri =
Platform.OS === 'ios'
? uploadImageFile.replace('file:', '')
: uploadImageFile;
// console.log(uploadUri);
const data = new FormData();
data.append('file', {
uri: uploadUri,
name: 'file',
type: 'image/jpg',
});
Axios.post(`${API.BASE_URL}/user/image`, data, {
headers: {
Authorization: token,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
setActivity(false);
setIsImageEdit(false);
console.log('success');
})
.catch((error) => {
setActivity(false);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
setIsImageEdit(false);
});
The error response I get is
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false, "_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json, text/plain, */*", "authorization": "7aeb23f62bd748c39c9e8652eb1056e2"}, "_incrementalEvents": false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey": "network_XMLHttpRequest_https://capi-test.beebl.io/user/image", "_requestId": null, "_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg", "_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown", "_url": "https://capi-test.beebl.io/user/image", "readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials": true}
"_response": "Could not retrieve file for uri /storage/emulated/0/Pictures/images/image-448777a5-1734-41f4-857e-a99d5239c279.jpg"
I fixed it by adding
android:requestLegacyExternalStorage="true"
in AndroidManifest.xml
Hey guys i am trying to fetch data from remote server and returning in alertbox using react-native
Here's my code for fetching
_onPressButtonPOST: function(){
fetch("http://www.example.com/endpoint", {
method: "POST",
body: JSON.stringify({
key: "value",
})
})
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData.body)
)
})
.done();
},
Here is what i want to fetch from my endpoints.
{
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "service",
"_type": "service",
"_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"_score": 1,
"_source": {
"service_owner_id": "2",
"service_name": "miamia",
"service_email": "mk#gmail.com",
"service_contact_name": "mukesh",
"service_landline_number": "12345",
"service_mobile_number": "1234567890",
"service_address": "vdvml",
"service_listingType": 1,
"service_avg_rating": 3.5,
"sarvice_ratingcount": 10,
"service_serviceType": 1,
"service_working_hour": [
""
],
"service_subcat_ids": "2,3",
"service_description": "hi I am mukesh kumar ",
"service_id": "ac8c5edd-1aad-406f-b476-012c6e940c1a",
"service_logo_url": "",
"service_gallery_url": "",
"service_location": {
"lat": 19.34,
"lon": 72.845
},
"service_subcategory": "CAT GER ",
"service_review": []
}
}
]
},
"took": 2,
"timed_out": false
}
But in alertbox it is showing undefined what might be the issue? can anyone help on this?
Thanks in advance.
Hey guys i found out the bug and consumed the API successfully thanks to https://www.thepolyglotdeveloper.com/2015/09/make-http-requests-in-ios-with-react-native/
I just replaced responseData.body with responseData as there was no body included in my server side code so it was returning undefined
Here is my sample code
.then((response) => response.json())
.then((responseData) => {
Alert.alert(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
})
.done();
Any doubts and queries are welcome.
Generally another reason is that, in PHP endpoint code they try to fetch the parameters sent by using $_POST, $_GET or $_REQUEST.
In that case, instead of Json, use FormData as body's value in your fetch operation.
An example
var FormDataToPost = new FormData();
FormDataToPost.append('userId', 12);
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: FormDataToPost
})
.then((response) => response.json())
.then((responseData) => { do something })
.catch((error) => {
alert(error);
})
.done();
I am setting headers and body , Using fetch with Post to upload image on server.I am getting the response code 200 but it is not uploading image but rest of the Data is getting uploaded.
Here is the code of body:
export default function setRequestBody(imagePath){
let boundry = "----WebKitFormBoundaryIOASRrUAgzuadr8l";
let body = new FormData();
body.append("--"+boundry+"\r\n");
body.append("Content-Disposition: form-data; name=imageCaption\r\n\r\n");
body.append("Caption"+"\r\n");
body.append("--"+boundry+"\r\n");
body.append("Content-Disposition: form-data; name=imageFormKey; filename =iimageName.pngg \r\n");
body.append("Content-Type: image/png \r\n\r\n");
body.append({uri : imagePath});
// appened image Data Here
body.append("\r\n");
body.append("--"+boundry+"--\r\n");
return body
}
Please help.What mistake I am making. :(
I've found the solution:
let body = new FormData();
body.append('photo', {uri: imagePath,name: 'photo.png',filename :'imageName.png',type: 'image/png'});
body.append('Content-Type', 'image/png');
fetch(Url,{ method: 'POST',headers:{
"Content-Type": "multipart/form-data",
"otherHeader": "foo",
} , body :body} )
.then((res) => checkStatus(res))
.then((res) => res.json())
.then((res) => { console.log("response" +JSON.stringify(res)); })
.catch((e) => console.log(e))
.done()
** filename is optional...
The problem is body.append({uri : imagePath}); because react native JSC does not support File and Blob, so you have to use libraries.
react-native-fetch-blob has very good support for this, example from its README.md
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
// custom content type
{ name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
// part file from storage
{ name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
// elements without property `filename` will be sent as plain text
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example#example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})
I've found the solution to Upload the Image on server in React Native:
const formdata = new FormData();
formdata.append('image[]', {
name: 'test.' + imageurl?.type?.substr(6),
type: imageurl?.type,
uri:
Platform.OS !== 'android'
? 'file://' + imageurl?.uri
: imageurl?.uri,
});
const res = await axios.post(url, formdata, {
headers: {
Accept: '*/*',
'Content-type': 'multipart/form-data',
},
});
//First Install and import Image-piker
//install
npm i react-native-image-picker
//import
import * as ImagePicker from 'expo-image-picker';
//then
const [image, setImage] = React.useState(null);
const [Type,setType]=React.useState('')
//Get the image
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
// extract the filetype
setType(result.uri.substring(result.uri.lastIndexOf(".") + 1));
setImage(result.uri);
}
};
//show image return
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Ecolher Foto" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 150, height: 150 }} />}
</View>
//UpLoad Image
var validatinoApi ='https://seusite.com/OOP/';
var headers={
'Accept':'application/json',
"Content-Type": "multipart/form-data",
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Origin':'*',
'crossDomain': 'true',
'Host': 'https://seusite.com/OOP/',
'Origin': 'https://origem.com',
};
/*'crossDomain': 'true',*/
var Data={
image:image,
namefoto: `photo.${namefoto}`,
type: `image/${Type}`
};
fetch(validatinoApi,
{
method:'POST',
headers:headers,
body:JSON.stringify(Data)
}).then((response)=>response.json())
.then((response)=>{
if(response.statusCode==200){
//Do something
}