Graphql Apollo Server + Vue => 图片上传

5
我可以帮助您进行翻译。以下是翻译的结果:

我在前端使用Vue和vue-apollo,在后端使用独立的Apollo Server 2和mongoose连接mongodb。我有一个简单的博客应用程序,其中文章还包括图片。除了上传图片之外,一切都运行良好。我希望将图片上传到我的后端文件系统中的一个文件夹,并仅将图像路径保存在我的mongodb文档中。

这是mutation:

 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()时,流(stream)和文件名(filename)未定义,但如果我记录(args.img),它是一个对象。并且将它们上传到我的本地文件夹也不起作用。任何帮助都将被赞赏,并标记为已接受的答案。

1个回答

0

如果您能分享您的GraphQL Schema,那就太好了,这样我们就可以看到您返回的类型。不过,以下是我在大多数应用程序中处理文件上传的方法。

GraphQL Schema

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

mongoose模式

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;
    },
  },
};

在这里你可以找到我写的一篇关于如何处理文件上传的文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接