Skip to content

Instantly share code, notes, and snippets.

@miracle2k
Created January 30, 2019 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miracle2k/70dcd29e5a577c81e5854b3bfa98767e to your computer and use it in GitHub Desktop.
Save miracle2k/70dcd29e5a577c81e5854b3bfa98767e to your computer and use it in GitHub Desktop.
function fetchWithProgress(url, opts={}, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(opts.method || 'get', url);
for (var k in opts.headers || {}) {
xhr.setRequestHeader(k, opts.headers[k]);
}
xhr.onload = e => {
if (xhr.status === 200) {
let json;
try {
json = JSON.parse(xhr.responseText);
} catch(e) {
reject(e);
return;
}
resolve(json);
} else {
reject({code: xhr.status, text: xhr.statusText});
}
};
xhr.onerror = reject;
if (xhr.upload && onProgress) {
xhr.upload.onprogress = (ev) => {
if (onProgress) {
const progress = ev.loaded / ev.total; //event.lengthComputable
onProgress({progress});
}
};
}
xhr.send(opts.body);
});
}
// React-Native has a special FormData mode:
// https://github.com/facebook/react-native/blob/56fef9b6225ffc1ba87f784660eebe842866c57d/Libraries/Network/FormData.js#L34
data = new FormData();
data.append('picture', ({
uri: urlToTheImageForExampleFromTheCamera,
type: 'image/jpeg',
name: 'picture'
}: any));
const promise = fetchWithProgress(`${this.baseUrl}/upload-profile-picture`, {
method: 'POST',
body: data,
headers: {
...this.getHeaders(),
'content-type': 'multipart/form-data'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment