Sending application files to the API

2

I have a React-native APP and an API with Laravel

The two are communicating correctly, sending APP data to the API and otherwise incorrectly

At the moment to send and receive requests in the APP I use axios

But now I would like to send APP files and images to the API

I can get the image address on my mobile phone

But from now on I do not know how to proceed

    
asked by anonymous 22.12.2017 / 18:27

1 answer

1

reactive-native upload

It 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)
)

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
    });
22.12.2017 / 18:44