小编mai*_*n.c的帖子

Graphql Apollo Server + Vue => 图片上传

我在前端使用带有 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)

javascript apollo vue.js graphql vuejs2

5
推荐指数
1
解决办法
583
查看次数

标签 统计

apollo ×1

graphql ×1

javascript ×1

vue.js ×1

vuejs2 ×1