How to send application files to the API

Asked

Viewed 1,395 times

2

I have an APP in React-Native and an API with Laravel

Both are communicating correctly, sending APP data to the API and otherwise correctly

Currently to send and receive requests in the APP I use the Xios

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

I can get the address of the image on the phone

But I don’t know how to proceed

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 called 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 so:

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
    });
  • Really, I’ll try here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.