Last active
February 6, 2023 12:30
-
-
Save lazypanda-instance/ad8822e65a0e8e41b851fa163d69fbdb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multer from "multer"; | |
/** | |
* For local directory | |
*/ | |
const storage = multer.diskStorage({ | |
destination: (req, file, cb) => { | |
cb(null, 'uploads'); | |
}, | |
filename: (req, file, cb) => { | |
cb(null, file.originalname); | |
} | |
}); | |
const imageFilter = (req: any, file: any, cb: any) => { | |
if (!file.originalname.match(/\.(JPG|jpg|jpeg|png|gif)$/)) { | |
return cb(new Error('Only image files are allowed!'), false); | |
} | |
cb(undefined, true) | |
}; | |
const processImageMiddleware = multer({ | |
fileFilter: imageFilter, | |
storage: multer.memoryStorage(), //storage | |
limits: { | |
fileSize: 5 * 1024 * 1024, // keep images size < 5 MB | |
}, | |
}).single('file'); | |
export default processImageMiddleware; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request, Response } from "express"; | |
import { checkPostRequestBody } from "../../middleware/checks"; | |
import { BlogController } from "./blogController"; | |
import FirebaseImageProvider, { IFileStatus } from "./providers/firebaseImageProvider"; | |
import UploadImageProvider from "./providers/imageProvider"; | |
import processImageMiddleware from "./providers/processImageMiddleware"; | |
export default [ | |
{ | |
path: "/api/v1/uploadImages", | |
method: "post", | |
handler: [ | |
checkPostRequestBody, | |
async (req: Request, res: Response, next: any) => { | |
processImageMiddleware(req, res, async (err) => { | |
if (!req.file) { | |
res.status(400).send('Please attach the file'); | |
return; | |
} | |
const file = req.file; | |
const firebaseImageProvider = new FirebaseImageProvider(req, res); | |
firebaseImageProvider.uploadImageToFirebase(file).then(async (file: IFileStatus) => { | |
if (file.isUploaded) { | |
const blogController = new BlogController(req); | |
const result = await blogController.uploadImage(undefined, file.filePath); | |
return res.status(200).send(result); | |
} | |
}).catch(error => { | |
return res.status(400).json({ | |
"status": "failed", | |
"code" : "400", | |
"message" : error.message | |
}); | |
}) | |
}); | |
} | |
] | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment