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

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.

Related

How do I use Async Storage to save Data Locally after calling fetch in react native?

I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

I am unable to get API data in redux store

I am trying to build an app to add and delete items. I am using an API(Link of API documentation below). I can post and get data from API to the store. But I am unable to show the saved items on UI. And the getBooks function seems to be not working. Can anyone please help me?
Link to API documentation: https://www.notion.so/Bookstore-API-51ea269061f849118c65c0a53e88a739
Here is the code, I have used.
export const addBook = (book) => async (dispatch) => {
await fetch(url, {
method: 'POST',
body: JSON.stringify(book),
headers:{
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(() => dispatch({type: ADD_BOOK, book}))
}
export const removeBook = (index) => async (dispatch) => {
await fetch(`${url}/${index}`, {
method: 'DELETE',
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(() => dispatch({ type: REMOVE_BOOK, index }));
};
export const getBooks = () => async (dispatch) => {
await fetch(url)
.then((res) => res.json())
.then((book) => {
const booksArray = [];
Object.keys(book).forEach((key) => {
booksArray.push({
item_id: key,
author: book[key][0].author,
title: book[key][0].title,
category: book[key][0].category,
});
});
dispatch({ type: GET_BOOKS, booksArray});
});
};

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

Success upload file via postman but fail on front-end (vue)

I have been success upload file via postman and file has been moved to the folder, but when I try on front-end (vuejs) nothing error but file is not moved,
_upload(){
let fd = new FormData();
fd.append('photo', this.photo); // this.photo is base64 data
this.axios.post('upload_photo', fd, {
headers: {
'content-type': 'multipart/form-data'
}
}
).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
try this:
First create the variable.
var photo = ref();
bind to input file tag
<input
id="photo"
type="file"
name="photo"
hidden
#change="previewImage"
#input="photo= $event.target.files[0]"
/>
This is the upload function
const uploadImg = () => {
var formData = new FormData();
formData.append("photo", photo);
(async () => {
await axios
.post(route("editImg"), formData, {
headers: {
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "multipart/form-data",
},
credentials: "same-origin",
})
.then((response) => {
console.log(response);
.catch((e) => {
console.log("err = ", e);
});
})();
};

FacePlusPlus, "error_message": "MISSING_ARGUMENTS: api_key", with React Native fetch request

I'm fairly new to react native and I'm trying to test out using the FacePlusPlus API (https://console.faceplusplus.com/documents/5679127).
Here, I've tried putting 'api_key' in the body, however, I've also tried putting it in headers too. Neither has worked.
componentDidMount() {
var url = 'https://api-us.faceplusplus.com/facepp/v3/detect';
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_key: 'blahblahblah',
api_secret: 'blahblahblah',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
In render(), I put console.log(this.state.data) where data is an array to see the response, however all I keep getting is
Object {
"error_message": "MISSING_ARGUMENTS: api_key",
}
To solve this problem you have to set Content-Type header to 'application/x-www-form-urlencoded'
and pass your arguments as formData.
I put the example with using 'request' npm package.
const request = require('request');
request.post({url:'https://api-us.faceplusplus.com/facepp/v3/compare', formData: {
api_key: 'your api key',
api_secret: 'your api secret',
image_url1: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/George_Lucas_cropped_2009.jpg/220px-George_Lucas_cropped_2009.jpg',
image_url2: 'https://imgix.bustle.com/uploads/getty/2018/6/13/e4c5921d-3e23-4f13-87fe-0180005d0ace-getty-929360234.jpg?w=970&h=582&fit=crop&crop=faces&auto=format&q=70'
}}, (err, httpResponse, body) => {
if (err) {
return console.error('error', err);
}
console.log('success ', JSON.parse(body));
});