Created
January 30, 2019 18:43
-
-
Save miracle2k/70dcd29e5a577c81e5854b3bfa98767e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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