【发布时间】:2019-04-30 20:18:30
【问题描述】:
我在前端使用带有 vue-apollo 的 Vue,在后端使用带有 mongodb 的 graphql 独立 Apollo Server 2。我有一个简单的博客应用程序,其中的帖子也有一个图像。除了上传图片外,一切正常。我希望将图像上传到后端文件夹中的本地文件系统,并且仅将图像的路径上传到我的 mongodb 文档中。
突变:
async createPost(parent, args, context, info) {
//...
const {stream, filename} = await args.img
const img_path = await upload({stream, filename})
const post = await Post.save({
//img is a string in my mongo model
img: img_path,
author_name: args.user.username,
author_email: args.user.email
});
}
应该返回路径并将图像保存到本地的上传方法:
const upload = ({ stream, filename }) => {
const id = shortid.generate()
const path = `${UPLOAD_DIR}/${filename}-${id}`
new Promise((resolve, reject) =>
stream
.pipe(fs.createWriteStream(filename))
.on("finish", () => resolve(path))
.on("error", reject(Error))
);
}
我得到的错误是调用upload() 时未定义流和文件名,但如果我记录它,args.img 是一个对象。并且将它们上传到我的本地文件夹也不起作用。任何帮助表示赞赏并标记为已接受的答案
【问题讨论】:
标签: javascript vue.js vuejs2 graphql apollo