如何确保在Node.js中存在给定文件的给定文件
首先,我正在与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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论