Skip to content

Commit

Permalink
feat: add support for S3 file upload
Browse files Browse the repository at this point in the history
  • Loading branch information
eowfenth committed Apr 29, 2020
1 parent dd7c115 commit deef9f4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/user/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ const disable = async (req, res) => {
};

const upload = async (req, res) => {
const { file, auth_user_id: user_id } = req;
const { file = null, auth_user_id: user_id } = req;

const picture = await User.upload({ url: file.filename, user_id });
const picture = await User.upload({ url: process.env.UPLOAD_STORAGE === "diskstorage" ? file.filename : file.location, user_id });

if (!picture || picture.error) {
return res.json(picture);
Expand Down
25 changes: 15 additions & 10 deletions src/utils/upload/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,24 @@ const fileCheck = (req, file, next) => {
};

const s3 = new AWS.S3({
accessKeyId: "",
secretAccessKey: "",
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY,
});

const s3fileUpload = multer({
const S3Storage = {
storage: multerS3({
s3: s3,
acl: 'public-read',
bucket: 'bucket-name',
bucket: 'matching-app-bucket',
metadata: (req, file, cb) => { cb(null, { fieldName: file.fieldname })},
key: (req, file, cb) => { cb(null, Date.now().toString() + '-' + file.originalName) },
key: (req, file, cb) => {
const uniquePrefix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const fileExtension = path.extname(file.originalname);
cb(null, uniquePrefix + fileExtension) },
}),
limits: { fileSize: 5*1024*1024 }, // 5mb
limits: { fileSize: 5 * 1024 * 1024 }, // 5mb
fileFilter: fileCheck,
});
};

const storage = multer.diskStorage({
destination: function (req, file, cb) {
Expand All @@ -40,11 +43,13 @@ const storage = multer.diskStorage({
},
});

const Uploader = multer({
const DiskStorage = {
storage,
limits: { fileSize: 5*1024*1024 },
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: fileCheck,
}).single('file');
};

const Uploader = multer(process.env.UPLOAD_STORAGE === "diskstorage" ? DiskStorage : S3Storage).single('file');

const fileUpload = (req, res, next) => {
Uploader(req, res, (err) => {
Expand Down

0 comments on commit deef9f4

Please sign in to comment.