I want to upload file(image, textfile, pdf etc) with FormData() and fetch request. Progress event working fine after completed progress event it gives {"response":{"code":400,"api_status":0,"message":"Error while reading image."}} .
How I can resolve this issue here is my code.
let uploadUrl = 'http://myurl.com:8080/api/v1/upload';
const data = new FormData();
data.append('name', 'testName');
data.append('photo', {
uri: 'content://com.android.providers.media.documents/document/image-234.jpg',
type: 'image/jpeg',
name: 'testPhotoName'
});
futch(uploadUrl, {
method: 'post',
body: data
}, (progressEvent) => {
const progress = progressEvent.loaded / progressEvent.total;
console.log(progress);
}).then((res) => console.log(res), (err) => console.log(err));
Related
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);
};
My React Native application receives a selected image using the react-native-image-picker library and I need to send that image to a back-end running a NestJS server. The endpoint uses #UseInterceptor and FileInterceptor to extract the image from the 'file' field of the formData received. However, when I fire the request to the endpoint, the file received is undefined.
Here is my React Native code sending the request with the file in the FormData as a payload.
const uploadNewProfileImage = async () => {
if (!newProfileImage?.assets) return;
const formData = new FormData();
const profileImage = newProfileImage.assets[0];
console.log(profileImage);
if (profileImage.uri && user) {
formData.append(
'file',
JSON.stringify({
uri:
Platform.OS === 'android'
? profileImage.uri
: profileImage.uri.replace('file://', ''),
name: profileImage.fileName,
type: profileImage.type
})
);
client // client is an Axios instance that injects Bearer Token
.post(`/user/profile/${user.uid}/image`, formData)
.then(({ data }) => {
console.log(data);
})
.catch((err) => {
console.log(err.response);
setShowImageUploadError(true);
})
.finally(() => {
getUserProfile();
});
}
};
Here is my back-end NestJS code extracting the file.
// User.controller.ts
#UseGuards(UserGuard)
#ApiBearerAuth()
#ApiUnauthorizedResponse({ description: 'Unauthorized' })
#UseInterceptors(FileInterceptor('file', { limits: { fileSize: 20000000 } }))
#Post('/profile/:uid/image')
#ApiOkResponse({ type: UploadProfileResponse })
#ApiBadRequestResponse({ description: 'Image too large OR Invalid image type' })
async uploadProfilePicture(#UploadedFile() file: Express.Multer.File, #Request() req): Promise<UploadProfileResponse> {
const uid = req.user.uid;
const imageUrl = await this.userService.uploadProfilePicture(uid, file);
return imageUrl;
}
}
I tried to set the axios request header in the axios config like so
{
headers: {
'Content-Type': 'multipart/form-data; boundary=——file'
}
}
I tried chaning the back-end endpoint to the following
#UseGuards(UserGuard)
#ApiBearerAuth()
#ApiUnauthorizedResponse({ description: 'Unauthorized' })
#UseInterceptors(FileFieldsInterceptor([{ name: 'file' }], { limits: { fileSize: 20000000 } }))
#Post('/profile/:uid/image')
#ApiOkResponse({ type: UploadProfileResponse })
#ApiBadRequestResponse({ description: 'Image too large OR Invalid image type' })
async uploadProfilePicture(#UploadedFiles() file: Array<Express.Multer.File>, #Request() req): Promise<UploadProfileResponse> {
const uid = req.user.uid;
console.log("File", file);
const imageUrl = await this.userService.uploadProfilePicture(uid, file[0]);
return imageUrl;
}
Nothing seems to be working, and the file extracted from the backend is still undefined.
Any help would be greatly appreciated.
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] ] } }
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'
}
})
I've tried to upload multiple images to server at a once by using fetch.
Here is my code chip.
chooseImage(){
ImagePicker.openPicker({
multiple: true,
waitAnimationEnd: false
}).then(images => {
var photos = []
images.map((image, i) => {
photos.push({
uri:image.path,
name: image.name,
type: 'image/jpg'
})
let source = {uri: image.path}
this.state.photos.push({image: source, check: true, hairstyle: '', price: ''})
})
var data = new FormData();
data.append('photos', photos)
const config = {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'multipart/form-data;',
'Authorization': this.props.auth.token
},
body: data,
}
fetch("http://**.***.***.***/api/providers/uploadPhotos", config)
.then(res=>res.json()).then((res) => {
console.log("----------Response----------")
console.log(res)
this._getStylist()
this.setState({photo_take: false});
}).catch(err=>{
console.log("------------Error-----------")
console.log(err)
console.log("error in uploading image")
}).done()
}).catch(e => {
console.log(e);
});
}
When I try it, I get 200 response from server and photos doesn't upload to server actually.
I searched the solution a few days, but couldn't find the suitable solution.
Thanks for any suggestion.
I am new at react native but seems like you can loop throght images array to upload images Maybe you can add this post actions in promise array then you can be sure that every photo added to your storage. I use promise array methods while working on my node js server project its very useful.
Edit for example:
var photos=[];
var promise_array=[];
photos.forEach(function(photo){
const config = {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'multipart/form-data;',
'Authorization': this.props.auth.token
},
body: photo,
}
promise_array.push(fetch("http://**.***.***.***/api/providers/uploadPhotos", config)
.then(res=>res.json()).then((res) => {
console.log("----------Response----------")
console.log(res)
this._getStylist()
this.setState({photo_take: false});
}).catch(err=>{
console.log("------------Error-----------")
console.log(err)
console.log("error in uploading image")
}).done())
})
Promise.all(promise_array);
Since fetch is a promise I can put in promise array. Maybe there is syntax error in example and I am not sure react native support promise methods fully but here is documentation for promise method I use https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all