Created
February 18, 2016 15:29
-
-
Save jsclayton/5bb00e051b5e354263c0 to your computer and use it in GitHub Desktop.
Upload file from the browser
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
import immutable from 'immutable'; | |
import request from 'superagent'; | |
import userSession from './store/userSession'; | |
const OAUTH_TOKEN = 'Authorization'; | |
function doRequest(req, headers={}) { | |
let token = userSession.store.current.get('access_token'); | |
if (token) { | |
headers[OAUTH_TOKEN] = `Bearer ${token}`; | |
} | |
return new Promise((resolve, reject) => { | |
if (headers !== undefined) { | |
req = req.set(headers); | |
} | |
req.withCredentials().end((error, response) => { | |
if (error || !response || !response.ok) { | |
reject(error || new Error('Unspecified error')); | |
} else if (!response.body && response.text) { | |
reject(new Error('Response was not parsed as JSON; was Content-Type set to application/json?')); | |
} else { | |
resolve(immutable.fromJS(response.body)); | |
} | |
}); | |
}); | |
} | |
export function uploadFile(url, contentType, data) { | |
return new Promise((resolve, reject) => { | |
request.put(url) | |
.send(data) | |
.type(contentType) | |
.end((error, response) => { | |
if (error || !response || !response.ok) { | |
reject(error || new Error('Unspecified error')); | |
} else { | |
resolve(url); | |
} | |
}) | |
}) | |
} | |
export default {uploadFile}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment