Skip to content

Instantly share code, notes, and snippets.

@musicm122
Created November 27, 2016 19:21
Show Gist options
  • Save musicm122/3d60022abd2258bedc5aa00dff261473 to your computer and use it in GitHub Desktop.
Save musicm122/3d60022abd2258bedc5aa00dff261473 to your computer and use it in GitHub Desktop.
Uploading a file to S3 in node.js
<html>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<div class="field">
<label for="image">Image Upload</label>
<input type="file" name="image" id="image">
</div>
<input type="submit" class="btn" value="Save">
</form>
</body>
</html>
var aws = require('aws-sdk')
aws.config.loadFromPath('./AwsConfig.json');
var express = require('express')
var multer = require('multer')
var multerS3 = require('multer-s3')
var guid = require('guid');
var app = express()
var s3 = new aws.S3()
var upload = multer({
storage: multerS3({
s3: s3,
acl: 'public-read',
contentType: multerS3.AUTO_CONTENT_TYPE,
bucket: 'yourbucket',
accessKeyId: 'yourid',
secretAccessKey: 'yoursecret',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
})
//open in browser to see upload form
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/upload', upload.single('image'), function(req, res, next) {
res.send('Successfully uploaded ' + req.file + '!')
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment