问题描述
我试图让用户选择在我的React-Native前端上传个人资料图片,并将其存储在我的MERN堆栈后端。我大致遵循了this教程。我正在使用multer,猫鼬和gridfs将图像上传到MongoDB Atlas。
问题:每次我从用户帐户上传图片时,multer都会使用新的元数据将其上传到mongodb。这导致用户 ever 上传的所有图像的累积。尽管这不会干扰检索和渲染,但我希望数据库仅保留用户上传的最新图片,并自动删除其他图片。 upload.files中的文件名是用户的JSON Web令牌,这就是我如何区分一个用户的图片和另一个用户的图片。
我的代码:
const connection = mongoose.createConnection(mongoURI,{ useUnifiedTopology: true,useNewUrlParser: true })
let gfs
connection.once('open',() => {
gfs = new mongoose.mongo.GridFSBucket(connection.db,{bucketName: 'uploads'});
console.log('Connected to DB')
})
// Storage
const storage = new GridFsstorage({
url: mongoURI,options: { useUnifiedTopology: true },file: (req,file) => {
return new Promise((resolve,reject) => {
crypto.randomBytes(16,(err,buf) => {
if (err) {
return reject(err);
}
const filename = req.body.userJWT
const fileInfo = {
filename: filename,bucketName: "uploads"
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage,fileFilter (req,file,cb) {
if(file.mimetype !== 'image/png' && file.mimetype !== 'image/jpeg'){
return cb(new Error(`File must be of JPEG or PNG format. Cannot upload picture of type ${file.mimetype}`),false);
}
cb(null,true)
} });
app.post('/',upload.single('img'),(req,res,err) => {
res.send(req.files);
})
app.get("/:filename",res) => {
const file = gfs
.find({
filename: req.params.filename
})
.toArray((err,files) => {
if (!files || files.length === 0) {
return res.status(404).json({
err: "no files exist"
});
}
gfs.openDownloadStreamByName(req.params.filename).pipe(res);
});
});
问题:有没有办法自动覆盖具有相同文件名的先前图像?我一直在寻找其他人提出的类似问题,但找不到任何问题。我还愿意接受其他实现,只要它连接到MongoDB Atlas实例,就可以根据用户文档存储个人资料图片。
任何提示/指导将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)