我有一个工作流,用户可以创建帖子并编辑帖子。当用户编辑帖子时,我正在使用Filepond显示文件。我正在执行GET请求,以获取与该特定帖子相关的文件。我为此设置了ExpressJS API路由:
router.get(
"/edit/:id/post-files",
passport.authenticate("jwt", { session: false }),
async (req, res, next) => {
const errors = {};
Post.findById(req.params.id).then(post => {
if (post.user == req.user.id) {
if (!post) {
errors.nopost = "There is no post file";
return res
.status(404)
.json(errors)
.end();
}
try {
if (post.postFiles) {
post.postFiles.map(file => {
fs.readFile(file.postFilePath, "base64", (err, data) => {
res.set("Content-Type", file.fileType);
return res.send(data);
});
});
}
} catch (err) {
res
.status(400)
.json({ noFileFound: "File was not found" })
.end();
}
} else {
res
.status(400)
.json({ notAuthorized: "You are not authorized" })
.end();
}
});
});
我无法通过fs.readFile
读取多个文件,我相信我需要为此做出承诺,但是由于缺乏经验/知识,我无法处理。
post.postFiles
对象的样子如下:
{ uploadedBy: { userId: xxxxxxx, name: 'Xxxx Xxxxxx' },
date: 2020-05-07T08:04:06.374Z,
_id: xxxxxxxxxxxxxxxxxxx,
postFilePath:
'post_files/2020-05-07T08:04:06.282Z93292137_2865616126820580_7650583162275233792_n.jpg',
fileName: '93292137_2865616126820580_7650583162275233792_n.jpg',
fileType: 'image/jpeg' }
{ uploadedBy: { userId: Xxxxxxxxxxxxxxxx, name: 'Xxxxx Xxxxx' },
date: 2020-05-07T08:04:06.374Z,
_id: xxxxxxxxxxxxxxxx,
postFilePath:
'post_files/2020-05-07T08:04:06.282Z94149024_1376513669200115_4087337221017829376_n.jpg',
fileName: '94149024_1376513669200115_4087337221017829376_n.jpg',
fileType: 'image/jpeg' }
这种方法正确吗?如果是这样的话,我怎么能兑现承诺呢?还是有更好的方法来解决这个问题?
谢谢。