How to upload image from react-native without using base64? - react-native

For a project we need to upload an image file which has memory above 2mb.\
which we are not able to upload through base64 conversion.
Any help could be usefull

Once you have your local image url using ImagePicker or some another solution, here's how you can send it to your server:
const formData = new FormData();
formData.append("image", { uri: imageUrl, name: 'image.jpg', type: 'multipart/form-data' })
fetch(yourUrl, {
method: "POST", {
'Content-Type': 'multipart/form-data',
},
body: formData
);

Use any request library e.g axios . Then try with form data. To pick the image from device/camera you can use react-native-image-picker.
import ImagePicker from 'react-native-image-picker'
ImagePicker.showImagePicker(options, response => {
console.log(response.data)
});

Below is what helped me.
In android/app/src/main/java/com/{yourProject}/MainApplication.java
comment the below line :
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
In android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java
comment in line 43 :
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
Code for image upload :
var formData = new FormData();
formData.append('UserId', 'abc#abc.com');
formData.append('VisitId', '28596');
formData.append('EvidenceCapturedDate', '09/10/2019 13:28:20');
formData.append('EvidenceCategory', 'Before');
formData.append('EvidenceImage', {
uri: Platform.OS === 'android' ? `file:///${path}` : path,
type: 'image/jpeg',
name: 'image.jpg',
});
axios({
url: UrlString.BaseUrl + UrlString.imageUpload,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
})
.then(function (response) {
console.log('*****handle success******');
console.log(response.data);
})
.catch(function (response) {
console.log('*****handle failure******');
console.log(response);
});

Related

Axios React upload jpg

I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.
My code here
const axiosMultipart = axios.create({
timeout: 3000,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data'
}
})
uploadDocs(token,type,photo){
let data = new FormData();
data.append('photo', photo);
data.append('type', type);
return axiosMultipart
.post(
`uploadDocs`,
{data},
{
headers: {
Authorization: token,
},
}
)
.then((response) => {
return response.data;
})
.catch((error) => console.log("uploadDocs: " + error));
};
Server response is error_code 400
What is wrong here?
Also I have code on php with a working request
Try With Below Code,
var photo = {
uri: file,
type: 'image/jpeg',
name: 'photo.jpg',
};
var FormData = require('form-data');
var form = new FormData();
form.append('photo', photo);
form.append('filetype', filetype);
axios({
method: 'post',
headers: {
"Accept": "application/json",
'Content-Type': 'multipart/form-data',
"Authorization": authData
},
data: form,
url: `${base_url}`,
}).then(async (result) => {
console.log("uploadFile detail Response===>", result);
}).catch((error) => {
console.log("uploadFile detail error===>", error);
callback({ status: false, result: error })
});

React Native: Not able to make post request for formData using axios or fetch

I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,

How to upload image to server in React Native

I'm trying to upload image by using React Native axios. But I get this response. I tried every solutions but it didn't work. I'm using react-native-image-picker to get image
{ result: null,
message: 'Wrong access',
error: true,
type: 'command_not_found' }
Here is my code
ImagePicker.showImagePicker(options, (response) => {
let formData = new FormData();
formData.append('image', { uri: response.uri, name: response.fileName, type:response.type });
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios({
url: "URL",
method: 'POST',
data: formData,
config
})
.then(result => console.log(result))
.catch(error => console.log(error))
}
Try with raw fetch api.
const createFormData = (photo) => {
const data = new FormData();
data.append("photo", {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
});
return data;
};
and then try to upload it again
fetch("http://localhost:3000/api/upload", {
method: "POST",
body: createFormData(photo)
});

Can't get a .post with 'Content-Type': 'multipart/form-data' to work Axios React Native

i'm trying to upload FormData which include text ,image,pdf etc
I am using axios.
Axios Call
const sellerRegister = params => {
console.log(params);
return dispatch => {
dispatch(servicePending());
return axios
.post(`${BaseUrl}/seller/register`, params, {
headers: {
Accept: "application/json",
"Content-type": `multipart/form-data; boundary=${params._boundary}`
}
})
.then(res => {
return dispatch(sellerRegisterSuccess(res));
})
.catch(err => {
return dispatch(serviceError(err.message));
});
};
};
Params in FormData
ServiceError
Provide solutions of this error. and also guide me am i doing this in right way or not ?
Thanks
Using the latest version of Axios, you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], { type: 'text/csv' }));
axios({
url: 'http://your_host/api/auth_user',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
use url instead of uri.
or
You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data;
boundary=someArbitraryUniqueString';

How to upload a file from asset-library to Express server in React Native?

I have my video file assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov and I am trying to now upload it to my Express server.
const uri = 'http://localhost:3000/upload';
const formData = new FormData();
formData.append('file', 'assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov');
fetch(uri, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data boundary=gc0p4Jq0M2Yt08jU534c0p'
},
body: formData
})
.then(res => {
console.log({ res });
})
.catch(err => {
console.log(err);
});
My Express Server API endpoint:
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file);
res.send('Done');
});
The console.log(req.file) returns undefined.
Do I need to do an extra step in between?
As per Gavin's comment, I tried out RNFetchBlob.
RNFetchBlob.fetch(
'POST',
'http://localhost:3000/upload',
{
'Content-Type': 'multipart/form-data'
},
[
{
name: 'file',
filename: 'vid.mov',
data: RNFetchBlob.wrap(file)
}
]
)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
My application crashes without any logs on Xcode or in the Debugger.