showing results for - "express delete image"
Brisa
24 Aug 2020
1const router = express.Router();
2const path = require("path");
3const fs = require('fs');
4var multer = require('multer')
5var upload = multer({ dest: 'uploads/' })
6
7router.get('/:folder/:id', async (req, res) => {
8    let filepath = path.join(__dirname + `/../images/${req.params.folder}/${req.params.id}.png`);
9    res.sendFile(filepath);
10});
11
12const upload = async (image, folder, id) => {
13
14    let dir = `images`;
15
16    if (!fs.existsSync(dir)) {
17        fs.mkdirSync(dir);
18    }
19
20    dir = `images/${folder}`;
21
22    if (!fs.existsSync(dir)) {
23        fs.mkdirSync(dir);
24    }
25
26    await image.mv(`images/${folder}/${id}.png`);
27
28    return `${config.DOMAIN}/images/${folder}/${id}`;
29}
30
31router.post('/:folder/:id', upload.single('file'), async (req, res) => {
32    try {
33
34        let image = req.files.image;
35
36        if (!image)
37            return res.status(400).send({ message: 'Image not provided!' });
38
39        const imageUrl = await upload(image, req.params.folder, req.params.id);
40
41        if (imageUrl)
42            res.status(201).send({ message: "Image uploaded", url: imageUrl });
43
44    } catch (e) {
45        res.status(400).send({ message: "Error uploading image!", error: e.toString(), req: req.body });
46    }
47});
48
49router.delete('/:folder/:id', async (req, res) => {
50    try {
51        fs.unlinkSync(`images/${req.params.folder}/${req.params.id}.png`);
52
53        res.status(201).send({ message: "Image deleted" });
54
55    } catch (e) {
56        res.status(400).send({ message: "Error deleting image!", error: e.toString(), req: req.body });
57    }
58});
59
60module.exports = router;