reactive-native upload
Ficaria algo como:
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)
});
Múltiplas fotos
const photos = [photo1, photo2, ...]
photos.forEach((photo) => {
data.append('photo', {
uri: photo.uri,
type: photo.type,
name: photos.name
});
});
fetch(url, opts);
Para implementar progresso do upload crie um arquivo chamado api.js
e adicione isto:
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
Como usar:
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
Agora no Axios, pode fazer assim:
Note que document.getElementById('arquivo').files[0]
pega o valor do <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
});