如何确保在Node.js中存在给定文件的给定文件

发布于 2025-02-09 21:21:08 字数 942 浏览 3 评论 0原文

首先,我正在与Node.js一起使用Express
我制作了一个代码,允许我将图像上传到multer到特定目录,这是它的简化版本:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'images')
    },
    filename: (req, file, cb) => {
        cb(null, "some_random_name.jpg")
    },
})

const upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (path.extname(file.originalname) != '.jpg')
            return cb("Invalid file type, try uploading a '.jpg' file")
        else
            cb(null, true)
    }
}).single('image')

router.post('/', (req, res) => {
    upload(req, res, (err) => {
        if (err) 
            return res.status(400).send({ error: err.message })
        else
            dbController.query(/* INSERT INTO images ... */)
        }
    )
})

该代码可完美地工作,但是当我将非现有文件提供给它时​​,它可以创建一个文件,就好像文件存在一样。
因此,要解决这个问题,我必须确保在上传之前确实存在该文件。 我该如何实施。

First of all I'm working with Node.JS with Express
I made a code that allows me to upload an image with multer to a specific directory, and here is a simplified version of it:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'images')
    },
    filename: (req, file, cb) => {
        cb(null, "some_random_name.jpg")
    },
})

const upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (path.extname(file.originalname) != '.jpg')
            return cb("Invalid file type, try uploading a '.jpg' file")
        else
            cb(null, true)
    }
}).single('image')

router.post('/', (req, res) => {
    upload(req, res, (err) => {
        if (err) 
            return res.status(400).send({ error: err.message })
        else
            dbController.query(/* INSERT INTO images ... */)
        }
    )
})

The code works perfectly, but when I give a non existing file to it, it creates a file as if the file existed.
So to solve this I have to make sure that the file really exists before uploading it.
How can I implement this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文