Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active February 22, 2023 18:30
Show Gist options
  • Save mattlockyer/532291b6194f6d9ca40cb82564db9d2a to your computer and use it in GitHub Desktop.
Save mattlockyer/532291b6194f6d9ca40cb82564db9d2a to your computer and use it in GitHub Desktop.
s3 upload as stream using req stream (extra info in request header)
const file = this.input.files[0];
//console.log(file);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', (e) => {
console.log(e.target.response);
});
xhr.open('POST', host + 'fileuploadstream', true);
xhr.setRequestHeader('body', JSON.stringify({ id: 'somebucketfolderid', fn: file.name }));
xhr.send(file);
const fileUploadStream = (req, res) => {
//get "body" args from header
const { id, fn } = JSON.parse(req.get('body'));
const Key = id + '/' + fn; //upload to s3 folder "id" with filename === fn
const params = {
Key,
Bucket: bucketName, //set somewhere
Body: req, //req is a stream
};
s3.upload(params, (err, data) => {
if (err) {
res.send('Error Uploading Data: ' + JSON.stringify(err) + '\n' + JSON.stringify(err.stack));
} else {
res.send(Key);
}
});
};
@spsneo
Copy link

spsneo commented Jun 27, 2017

This does not work properly with express. Am I missing something?

@parthdesai93
Copy link

@spsneo are you using express bodyParser? using that might remove req.files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment