React native upload file
Is it possible to upload file (images) to server with react-native using FormData? Tried to use it like this:
const data = new FormData();
data.append('file', {uri: 'file://' + fileObject.uri, name: 'image.jpg', type: 'image/jpg;'});
const request = {
method: method,
mode: 'cors',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d',
},
body: data
}
return fetch(`${API}/${url}`, request).then((response) => {
return Promise.all([Promise.resolve(response), response.json()]);
})
For web FormData works as expected but for react-native no.
Tried to use react-native-fetch-blob
but here is no ability to use credentials
( important for me ) so server sending unauthorized
Hope your help!
For image pick using react-native-image-picker
I faced the same problem and FormData worked for me. I also using react-native-image-picker.
export const updateProfileData = (authToken, values) => {
const data = new FormData();
Object.keys(values).forEach(paramKey => {
if (paramKey === 'birthday') {
data.append(`profile[${paramKey}]`, moment(values[paramKey]).format('YYYY-M-D'));
} else if (paramKey === 'avatar') {
const photo = {
uri: values[paramKey].uri,
type: values[paramKey].type,
name: values[paramKey].fileName,
};
data.append(`profile[${paramKey}]`, photo);
} else {
data.append(`profile[${paramKey}]`, values[paramKey]);
}
});
return axios({
method: 'PATCH',
url: `${BASE_URL}/api/v1/current_profile`,
headers: {
'Auth-Token': authToken
},
data
})
.then((res) => {
return res.data;
});
};
The photo
built using data from the image picker.
also there is an axios
in example, but also should work with fetchAPI.
I implemented the same feature (photo upload) using the POST a method and Content Type as multipart/form-data
. I also used react-native-image-picker
.
var ImagePicker = require('react-native-image-picker')
function makeid(){
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function doUpload(image) {
let API_URL = "API_URL"
let fileURL = image
let picName = makeid() + '.jpg'
let data = new FormData()
if (fileURL) {
data.append('file', {uri: fileURL, name: picName, type: 'image/jpg'})
}
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d',
'Content-Language': 'en'
},
body: data,
}
return fetch(API_URL, config)
.then(response => response.json().then(photo => ({photo, response})))
.then(({photo, response}) => {
if(!response.ok) {
return Promise.reject(photo)
} else {
profileImage = photo.url
}
}).catch(err => {
console.log(err.message)
})
}
Comments
Post a Comment