【问题标题】:Graphql Apollo Server + Vue => Image UploadGraphql Apollo Server + Vue => 图片上传
【发布时间】: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


    【解决方案1】:

    很高兴分享您的 graphql Schema,以便我们可以看到您返回的类型。但是,这是我在大多数应用程序中处理文件上传的方式。

    graphql 模式

    type File {
        id: ID!
        filename: String!
        mimetype: String!
        path: String!
      }
    

    猫鼬模式

    import { Schema, model } from "mongoose";
    const fileSchema = new Schema({
      filename: String,
      mimetype: String,
      path: String,
    });
    export default model("File", fileSchema);
    

    存储上传的功能:

    const storeUpload = async ({ stream, filename, mimetype }) => {
      const id = shortid.generate();
      const path = `images/${id}-${filename}`;
      // (createWriteStream) writes our file to the images directory
      return new Promise((resolve, reject) =>
        stream
          .pipe(createWriteStream(path))
          .on("finish", () => resolve({ id, path, filename, mimetype }))
          .on("error", reject)
      );
    };
    

    处理上传

    const processUpload = async (upload) => {
      const { createReadStream, filename, mimetype } = await upload;
      const stream = createReadStream();
      const file = await storeUpload({ stream, filename, mimetype });
      return file;
    };
    

    变异

    export default {
      Mutation: {
        uploadFile: async (_, { file }) => {
          mkdir("images", { recursive: true }, (err) => {
            if (err) throw err;
          });
          const upload = await processUpload(file);
          // save our file to the mongodb
          await File.create(upload);
          return upload;
        },
      },
    };
    

    Here you can find an article i wrote on how to handle file uploads

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 2021-03-02
      • 2020-06-21
      • 1970-01-01
      • 2021-12-10
      • 2019-09-29
      • 2020-07-07
      • 2018-02-01
      • 2019-09-01
      相关资源
      最近更新 更多