Skip to content

Instantly share code, notes, and snippets.

@vovkasm
Created December 6, 2018 14:57
Show Gist options
  • Select an option

  • Save vovkasm/b84eb93b0d2fb51bc734d421703bd8fd to your computer and use it in GitHub Desktop.

Select an option

Save vovkasm/b84eb93b0d2fb51bc734d421703bd8fd to your computer and use it in GitHub Desktop.
Sample of uploading file in react-native
type Body = string | FormData | { uri: string } | ArrayBufferLike | ArrayBufferView
interface IUploadOptions {
body?: Body
headers?: { [k: string]: string }
method?: 'GET' | 'POST'
}
function upload(
url: string,
opts: IUploadOptions = {},
onProgress?: (ev: ProgressEvent) => any,
): Promise<XMLHttpRequest> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(opts.method || 'GET', url)
const headers = opts.headers || {}
for (const k in headers) {
if (headers.hasOwnProperty(k)) {
xhr.setRequestHeader(k, headers[k])
}
}
xhr.onload = (e) => resolve(e.target as XMLHttpRequest)
xhr.onerror = reject
if (xhr.upload && onProgress) {
xhr.upload.onprogress = (ev: Event) => {
onProgress(ev as ProgressEvent) // event.loaded / event.total * 100 ; //event.lengthComputable
}
}
xhr.send(opts.body)
})
}
// somewerre in the component
// uploadUrl - url to server, may be with some get parameters like "https://my-server.org/upload?sessionId=123&fileName=file"
// fileUri - a path to file, like "file:///some-path/image.png"
const uploadOpts: IUploadOptions = { body: { uri: fileUri }, method: 'POST' }
const onProgress = (ev: ProgressEvent) => {
const progress = ev.loaded / ev.total
...
}
upload(uploadUrl, uploadOpts, onProgress)
.then((xhr) => {
const rawResponse = xhr.response
if (typeof rawResponse !== 'string') {
return Promise.reject(new Error('UPLOAD FAILED'))
}
// this is our own logic, server returned JSON
const response: { success?: boolean; imageUrl?: string; error?: string } = JSON.parse(rawResponse)
if (!response || !response.success || !response.imageUrl) {
return Promise.reject(new Error('UPLOAD FAILED'))
}
return Promise.resolve()
})
.catch((e: Error) => {
// do something with error
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment