Skip to content

Commit c942fb8

Browse files
committed
upload images to s3
1 parent d75a0d4 commit c942fb8

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
uploads
22
saved
3+
credentials

image-upload.js

+27-4
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,17 @@
33
const path = require('path')
44
const isImage = require('is-image')
55
const uuid = require('uuid')
6+
const mime = require('mime-types')
7+
const S3 = require('aws-sdk/clients/s3')
68
const { send } = require('micro')
7-
const { upload, move } = require('micro-upload')
9+
const { upload } = require('micro-upload')
10+
11+
const s3 = new S3({
12+
region: 'us-west-2',
13+
params: { Bucket: 'medellinjs-microservicios' },
14+
accessKeyId: process.env.AWS_ACCESS_KEY,
15+
secretAccessKey: process.env.AWS_SECRET_KEY
16+
})
817

918
//
1019
// This microservice will be served as /upload
@@ -28,8 +37,22 @@ module.exports = upload(async (req, res) => {
2837
let ext = path.extname(file.name)
2938
let name = uuid.v4() + ext
3039

31-
// src: file object, dst: path
32-
await move(file, path.join(__dirname, 'uploads', name))
40+
const result = await s3move(name, file.data)
3341

34-
send(res, 200, { name: name, src: `/uploads/${name}` })
42+
send(res, 200, { name: name, src: result.Location })
3543
})
44+
45+
function s3move (name, data) {
46+
return new Promise((resolve, reject) => {
47+
s3.upload({
48+
Key: `uploads/${name}`,
49+
Body: data,
50+
ACL: 'public-read',
51+
ContentType: mime.lookup(name)
52+
}, (err, data) => {
53+
if (err) return reject(err)
54+
55+
resolve(data)
56+
})
57+
})
58+
}

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
},
1414
"homepage": "https://github.com/julianduque/microservices-demo#readme",
1515
"dependencies": {
16+
"aws-sdk": "^2.43.0",
1617
"instagram_js_filter": "^1.4.0",
1718
"is-image": "^1.0.1",
1819
"micro": "^7.3.2",

0 commit comments

Comments
 (0)