如何使用node.js和express上传,显示和删除图像

时间:2019-02-11 10:28:58

标签: node.js express server image-uploading

我需要将图像上传到服务器(内置于nodejs中),并在html站点中向所有人显示。当某人做同样的事情时,最后一张图像可能消失了,我不需要存储它。 有人可以帮我吗? 最好

2 个答案:

答案 0 :(得分:1)

希望这会有所帮助

在此示例中,如果您传递的ID和文件夹相同,则替换文件,请根据您的要求进行更改

我用过multer

const router = express.Router();
const path = require("path");
const fs = require('fs');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })

router.get('/:folder/:id', async (req, res) => {
    let filepath = path.join(__dirname + `/../images/${req.params.folder}/${req.params.id}.png`);
    res.sendFile(filepath);
});

const upload = async (image, folder, id) => {

    let dir = `images`;

    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }

    dir = `images/${folder}`;

    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }

    await image.mv(`images/${folder}/${id}.png`);

    return `${config.DOMAIN}/images/${folder}/${id}`;
}

router.post('/:folder/:id', upload.single('file'), async (req, res) => {
    try {

        let image = req.files.image;

        if (!image)
            return res.status(400).send({ message: 'Image not provided!' });

        const imageUrl = await upload(image, req.params.folder, req.params.id);

        if (imageUrl)
            res.status(201).send({ message: "Image uploaded", url: imageUrl });

    } catch (e) {
        res.status(400).send({ message: "Error uploading image!", error: e.toString(), req: req.body });
    }
});

router.delete('/:folder/:id', async (req, res) => {
    try {
        fs.unlinkSync(`images/${req.params.folder}/${req.params.id}.png`);

        res.status(201).send({ message: "Image deleted" });

    } catch (e) {
        res.status(400).send({ message: "Error deleting image!", error: e.toString(), req: req.body });
    }
});

module.exports = router;

答案 1 :(得分:0)

有许多教程和npm软件包可用于使用nodejs上传文件

Multer

Express Fileupload

Fileupload

Ng2 File Upload

Here,您可以找到一个教程