Skip to content

Instantly share code, notes, and snippets.

@jsclayton
Created February 18, 2016 15:29
Show Gist options
  • Save jsclayton/5bb00e051b5e354263c0 to your computer and use it in GitHub Desktop.
Save jsclayton/5bb00e051b5e354263c0 to your computer and use it in GitHub Desktop.
Upload file from the browser
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