【问题标题】:can we use Multer with graphql to upload files?我们可以使用带有 graphql 的 Multer 上传文件吗?
【发布时间】:2023-02-15 17:08:56
【问题描述】:

我正在寻找一些资源来通过 graphql mongodb 和 Multer 实现文件上传,但我只看到教程和与 rest-api 和 multer 相关的东西所以如果你能在这种情况下提供帮助请告诉我你的意见

我正在寻找一些资源来通过 graphql mongodb 和 Multer 实现文件上传,但我只看到教程和与 rest-api 和 multer 相关的东西所以如果你能在这种情况下提供帮助请告诉我你的意见

【问题讨论】:

    标签: api graphql multer


    【解决方案1】:
    image.Resolver.js ->
    const { createWriteStream } = require("fs");
    const { join } = require("path");
    const { graphqlUploadExpress } = require("graphql-upload");
    
    const storeUpload = async ({ stream, filename }) => {
      const uploadDir = "./uploads";
      const path = join(uploadDir, filename);
      return new Promise((resolve, reject) =>
        stream
          .pipe(createWriteStream(path))
          .on("finish", () => resolve({ path }))
          .on("error", reject)
      );
    };
    
    const processUpload = async (upload) => {
      const { createReadStream, filename, mimetype } = await upload;
      const stream = createReadStream();
      const { path } = await storeUpload({ stream, filename });
      return { filename, mimetype, path };
    };
    
    module.exports = {
      upload: graphqlUploadExpress().single("file"),
      Mutation: {
        uploadFile: async (_, { file }) => {
          const result = await processUpload(file);
          const newFile = await File.create(result);
          return newFile;
        },
      },
    };
    
    image.Schema.js ->
    module.exports = `
    type File {
        id: ID!
        filename: String!
        mimetype: String!
        path: String!
      }
      scalar Upload 
       
      type Mutation {
        uploadFile(file: Upload!): File!
      }`;
    
    File.js ->
    'use strict';
    module.exports = mongoose => {
      const newSchema = new mongoose.Schema({
        filename: {
          type: String
        },
        mimetype: {
          type: String
        },
        path: {
          type: String
        }
      }, {
        timestamps: {
          createdAt: 'created_at',
          updatedAt: 'updated_at'
        }
      });
      const image = mongoose.model('image', newSchema);
      return image;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多