以下代码可以正常工作以上传和检索文件:
// Mongo URI
const mongoURI = 'mongodbconnstring';
// // Create mongo connection
const conn = mongoose.createConnection(mongoURI);
// // Init gfs
let gfs;
conn.once('open', () => {
gfs = new mongoose.mongo.GridFSBucket(conn.db, {
bucketName: 'Uploads'
});
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
const filename = file.originalname; //+ Date.now();
const fileInfo = {
filename: filename,
bucketName: 'Uploads'
};
resolve(fileInfo);
});
}
});
const upload = multer({ storage });
// // @route POST /upload
// // @desc Uploads file to DB
routerUpload.post('/upload', upload.single('files'), (req, res) => {
//res.json({file: req.file})
res.redirect('/');
});
// @route GET /files
// @desc Display all files in json
routerUpload.get('/files', (req, res) => {
gfs.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
return res.json(files);
});
});
// @route GET /files/:filename
// @desc Display single file object
routerUpload.get('/files/:filename', (req, res) => {
const file = gfs
.find({
filename: req.params.filename
})
.toArray((err, files) => {
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
gfs.openDownloadStreamByName(req.params.filename).pipe(res);
});
});
但是,当我调用下面的代码以按ID删除文件时:
// @route DELETE /files/:id
// @desc Delete file
routerUpload.post('/files/del/:id', (req, res) => {
gfs.delete(req.params.id, (err, data) => {
if (err) {
return res.status(404).json({ err: err.message });
}
res.redirect('/');
});
});
我在邮递员中收到此错误:
{
"err": "FileNotFound: no file with id 5db097dae62a27455c3ab743 found"
}
有人能指出我该怎么做的方向吗?我尝试使用delete方法而不是post方法,甚至指定了文件的根目录,但是发生相同的错误。谢谢!
答案 0 :(得分:0)
您尝试过
// @route DELETE /files/:id
// @desc Delete file
routerUpload.post('/files/del/:id', (req, res) => {
gfs.remove({ _id: req.params.id, root: "uploads" }, (err, gridStore) => {
if (err) {
return res.status(404).json({ err });
}
return;
});
});
但是我使用的是旧版Express,因此收到了
(节点:6024)DeprecationWarning:不建议使用collection.remove。改用deleteOne,deleteMany或bulkWrite。
和
(节点:6024)不推荐使用警告:猫鼬:
findOneAndUpdate()
和findOneAndDelete()
(未将useFindAndModify
选项设置为false)
这是由于我使用的express,multer和GridFs版本