我在前端使用带有 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
});
}
Run Code Online (Sandbox Code Playgroud)
应该返回路径并将图像保存到本地的上传方法:
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", () …Run Code Online (Sandbox Code Playgroud)