Graphql Apollo服务器+ Vue =>图片上传

时间:2018-11-28 20:35:24

标签: javascript vue.js vuejs2 graphql apollo

我在前端使用Vue和vue-apollo,在后端使用带有mongodb的graphql独立Apollo Server 2和mongoose。我有一个简单的博客应用程序,其中的帖子也有一个图像。除了上传图片,一切都正常。我希望将图像上传到后端文件夹中的本地文件系统中,而仅将图像的路径保存在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是一个对象。并且将它们上传到我的本地文件夹均无效。感谢所有帮助并将其标记为接受的答案

1 个答案:

答案 0 :(得分:0)

最好共享您的graphql模式,以便我们可以看到您返回的类型。但是,这就是我在大多数应用程序中处理文件上传的方式。

graphql-schema

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