How to send application files to the API
I have an APP in React-native and an API with Laravel
The two are communicating correctly, sending data from the APP to the API and the other way around correctly
At the moment to send and receive requests in the APP I use axios
But now I would like to send files and images from the app to the API
I can get the address of the image on the mobile phone
But then on I don't know how to proceed
2
1 answers
Reactive-native upload
Would look something like:
const data = new FormData();
data.append('campo_foto_use_no_laravel', {
uri: photo.uri,
type: 'image/jpeg', // ou photo.type
name: 'minhaFoto' // ou photo.name
});
fetch(url, {
method: 'post',
body: data
}).then(res => {
console.log(res)
});
Multiple photos
const photos = [photo1, photo2, ...]
photos.forEach((photo) => {
data.append('photo', {
uri: photo.uri,
type: photo.type,
name: photos.name
});
});
fetch(url, opts);
To implement upload progress create a file named api.js
and add this:
const futch = (url, opts={}, onProgress) => {
console.log(url, opts)
return new Promise( (res, rej)=>{
var xhr = new XMLHttpRequest();
xhr.open(opts.method || 'get', url);
for (var k in opts.headers||{})
xhr.setRequestHeader(k, opts.headers[k]);
xhr.onload = e => res(e.target);
xhr.onerror = rej;
if (xhr.upload && onProgress)
xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
xhr.send(opts.body);
});
}
export default futch
How to use:
import futch from './api'; //Importa o asp.js
const data = new FormData();
data.append('name', 'testName');
data.append('photo', {
uri: source.uri,
type: 'image/jpeg',
name: 'testPhotoName'
});
futch(url, {
method: 'post',
body: data
}, (progressEvent) => {
const progress = progressEvent.loaded / progressEvent.total;
console.log(progress); //Exibe o progress
}).then(
(res) => console.log(res),
(err) => console.log(err)
)
- source: https://github.com/g6ling/React-Native-Tips/tree/master/How_to_upload_photo%2Cfile_in%20react-native
Axios
Now in Axios, you can do this:
Note that
document.getElementById('arquivo').files[0]
takes the value of<input type="file" name="arquivo" id="arquivo">
var data = new FormData();
data.append('file', document.getElementById('arquivo').files[0]);
//Configura a barra de progresso
var config = {
onUploadProgress: function(progressEvent) {
var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
console.log(percentCompleted);
}
};
axios.put('URI da API', data, config)
.then(function (res) {
console.log(res.data); //Resposta HTTP
})
.catch(function (err) {
console.log(err.message); //Erro HTTP
});
- brief documentation: https://github.com/axios/axios
1
Author: Guilherme Nascimento, 2017-12-22 17:50:09