React native im trying to upload image everytime localuri.slpit not defined showing and {_parts:[[]]} and why this _parts coming while sending data - react-native

can anyone tell me what wrong with this code im trying to upload image using react-native-image-picker in react native.but it says localUri.split is not defined and sending data shows in inspect element as {_parts:[[]]} and why this _parts coming every post method ...please help me to figure out this..
const takeAndUploadPhotoAsync = async () => {
const token = await AsyncStorage.getItem("userToken");
let result = await launchImageLibrary();
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop().split('#')[0].split('?')[0]
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
const url = `/auth/upload-prescription`;
let formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
setLoading(true);
const response = await api
.post(url, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
showMessage({
message: "Your Prescription is Uploaded Successfully",
textStyle: {textAlign:'center'},
type: "success",
backgroundColor: "#202877",
});
})
.catch((error) => {
console.log(error.response);
});
dispatch({
type: "TAKE_AND_UPLOAD_PHOTO_ASYNC",
payload: response,
});
setLoading(false);
};

Related

Upload Image With Expo & Fetch

I am trying to upload an image from my react native app.
If I use my local node server and run this code:
var fs = require("fs");
var options = {
method: "POST",
url: "my_URL",
headers: {},
formData: {
file: {
value: fs.createReadStream("../../assets/image.png"),
options: {
filename: "image.jpg",
contentType: null
}
}
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
I have a succesful upload.
However, with the URI from that we get through the the app, it does not work:
Here is my code on React Native Expo:
const body = new FormData();
body.append("file", 'file:///path/to/file/image123.jpg');
fetch(url, {
method: "POST",
body,
headers: {
"content-type": "multipart/form-data"
}
})
.then(response => {
console.log(response, "RESPONSE");
})
.then(result => {
console.log(result, "RESULT");
})
.catch(error => {
console.log(error, "ERROR");
});
I am unable to get it to work. I think it has something to do with the file path from the device.
Any help will be appreciated.
try to create FormData using this function
const createFormData = (uri) => {
const fileName = uri.split('/').pop();
const fileType = fileName.split('.').pop();
const formData = new FormData();
formData.append('file', {
uri,
name: fileName,
type: `image/${fileType}`
});
return formData;
}
if it doesn't work check permissions

When we call a api with post request it's showing [Error: Network Error]

Showing network error when i call the post api in react native and i am using axios.
Here is my code
export const walletRequest = async () => {
let config = {
headers: {
userID: 'BLOCALEVIG',
password: 'bloc#!2#22ev!g',
'Content-type': 'Application/json',
Accept: 'Application/json',
},
};
let data = {
mfsapiin: {
ReqService: 'WAL_API_WALLETSCREEN',
mobileNumber: '8639833477',
},
};
let url = `https://app.blocal.co.in:5959/mfmbs/mbintf/ina/processwalletapirequest.jsp?mfsapiin={
"ReqService":"WAL_API_WALLETSCREEN",
"mobileNumber":"8639833477"
}`;
const walletCheck = await axios
.post(url, data, config)
.then(resp => console.log('walletRequest.resp', resp))
.catch(error => console.log('walletRequest.err', error));
console.log('walletCheck', walletCheck);
};
Kindly tell me what is wrong in my code

React native cli formdata is sending data in a object it should not be in any object and array

im trying to post data using formdata but formdata sending data in a object..it should not be in any object or array,,in Reactjs web its working fine it just send like this lab_id : 1 ..how can i solve this issue ..please let me know what can i do,,,
//data is sending like this
{"_parts" : [[
['date', current_date],
['test_ids[]', tests_data],
['lab_partner_id', lab_id],
['booking_for', selectedMember],
['time', time_slot],
['health_package_id', health_packages_details],
['payment_mode', payment_mode],
]]},
// it should be like this only
health_package_id: health_packages_details
//my code
const onPay = async (
current_date,
tests_data,
lab_id,
selectedMember,
time_slot,
health_packages_details,
payment_mode,
) => {
const token = await AsyncStorage.getItem('userToken');
dispatch(startSubmitting());
const url = `/auth/make-booking`;
let formdata = new FormData();
formdata.append('lab_partner_id', lab_id);
formdata.append('booking_for', selectedMember);
formdata.append('date', current_date);
formdata.append('time', time_slot);
health_packages_details &&
formdata.append('health_package_id', health_packages_details);
tests_data && formdata.append('test_ids[]', tests_data);
formdata.append("payment_mode", payment_mode);
const response = await api
.post(
url, formdata ,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log("res hhh", res);
if (res.data.payment_mode == "ONLINE") {
initiatePaymentInterface(res.data);
}
dispatch({
type: 'BOOKING',
payload: response,
});
setLoading(false);
initiatePaymentInterface(res.data);
return res;
})
.catch(error => {
actions.setErrors(error.response.data.error);
failedPaymentInitiate(error.response);
setLoading(false);
});
dispatch(stopSubmitting());
};

Passing formData to upload image with nodeJS (Multer) -> 'react-native-image-crop-picker'

I have currently a problem when i want to uploads files from client mobiles devices to my backend (NodeJS) with MULTER.
I'm using 'react-native-image-crop-picker' to pick the images on the devices (from the library or the camera)
I have used formData to make the response as file to the backend but the req file is still undefined.
My front-end Code:
let response = await ImagePicker.openCamera({
height: 400,
width: 400,
cropping: true,
});<br>
let media = {
uri: response.path,
type: response.mime,
name: response.filename,
};<br>
let form = new FormData();
form.append('uploads', media);<br>
if (form !== null) {<br>
await Axios({
method: 'POST',
url: url,
data: form,<br>
headers: {
'Content-Type': 'multipart/form-data',
},
})
My backend :
router.post('/article', upload.single('uploads'), async (req,
res) =>
{<br>
try {
console.log(req.file);
} <br>catch (err) {
console.log(err.message);<br>
res.status(500).send('SERVOR ERROR');
}
});
front-end
back-end
console.log(req.file) = "UNDEFINED"
I have used to try with fs.readFile :
let d = {};
let e = await Fs.readFile(response.path, 'base64');
let form = new FormData();
form.append('uploads', e);
d.uploads = form;
let config = {'Content-Type': 'multipart/form-data'};
Axios.post(url, d, config)
.then((res) => console.log(res))
.catch((err) => console.error(err));
}
The req.file is still undefined but the req.body shows this :
req.file => undefined
req.body => { uploads: { _parts: [ [Array] ] } }

Network Error when sending file in react native with axios

I am trying to send a file to a nodejs server from react native using axios, this is my code:
const createFormData = (file) => {
const data = new FormData();
data.append('message', text);
data.append('receiver',doctorid);
if(file !== ''){
data.append('file', {
type: file.type,
uri: file.uri,
name: file.name.replace(/\s/g,'')
})
}
return data;
}
const onSend = async() => {
const newMessages = [...messages]
newMessages.push({"sender": currentuserID, "id": 339, "message": 'sending...', "attachment": '', "receiver": doctorid, "type": 0},)
setMessages(newMessages)
const token = await AsyncStorage.getItem('token');
const data = createFormData(singleFile)
await appApi.post('/chats', data, {
headers: { 'Authorization': 'Bearer ' + token }
}).then(()=>{
socket.emit('sendmessage', text, (err) => {
messageInit()
});
})
.catch(err => console.log(err.message))
}
This code works perfectly if there's no image attached, but ones there's an image attached, I get the network error message immediately.
For a little bit of troubleshooting, I tried sending request to my local machine, using ngrok. From ngrok, I realized the request wasn't sent at all to the url. So it just fails immediately, without the request been made to the url.
Anyone with solution to this.
I'm testing on an android emulator
send using formdata
try this
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})