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

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] ] } }

Related

how make put axios request with formData?

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

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

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

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);
};

Getting Network Error when trying to send Image to pre-signed URL in React Native

In my react native project I need to be able to send Images using axios to an API. For that I have the following function:
export function SetImage(image, id, token)
{
const formData = new FormData();
formData.append('file',{
uri: image.uri,
type: image.type,
})
return axios({
method: 'PUT',
url: axios.defaults.baseURL + "/api/SetImage/"+ID,
headers: {
'Content-Type': 'multipart/form-data' ,
'Authorization': 'Bearer: '+token,
},
data: formData
})
}
Image is the return Object I got from ImagePicker.launchImageLibraryAsync function which looks something like this:
{
"cancelled": false,
"height": 2048,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/<PathtoSomewhere>/ImagePicker/1d408e33-b54a-4189-
ac66-bd86ec11069a.jpg",
"width": 946,
}
However when I try to use the function I get the following error, that doesn't tell me anything:
Network Error
at node_modules\axios\lib\core\createError.js:16:14 in createError
at node_modules\axios\lib\adapters\xhr.js:84:13 in handleError
- ... 9 more stack frames from framework internals
I recently have to add same functionality to my project (upload image trough a pre-signed URL). This one is the ones that works for me:
const uploadImage = async ({ method, url, file }: any) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', file.type);
xhr.onload = () => {
if (xhr.status !== 200) {
reject(
new Error(
`Request failed. Status: ${xhr.status}. Content: ${xhr.responseText
}`,
),
);
}
resolve(xhr.responseText);
};
xhr.send(file);
});
};
// image === image inside local phone
export const uploadImageToUrl = async ({ image, url }: any) => {
await uploadImage({
method: 'PUT', url, file: {
uri: image.uri,
type: image.type,
}
});
return { url };
};
To upload an image, you just need to call it like:
uploadImageToUrl({ url: your-upload-url, image: your-image-object-from-image-picker })
Note: pass the whole image object to the function (not just the uri)
Also add this line if necessary:
xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken);

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'
}
})