繁体   English   中英

使用 GraphQL 和 Dropzone 上传文件

[英]Upload a file with GraphQL and Dropzone

我想知道如何使用 GraphQL 将文件上传到 API。

目前,当我记录文件时,我有这个:

在此处输入图像描述

但是当我执行突变时,我有这个错误“400 Bad Request”:

在此处输入图像描述

在我的组件中:

<dropzone id="foo" ref="el" :options="options" @vdropzone-file-added="sendingFile"></dropzone>

...

sendingFile(file) {
  console.log(file)

  this.$store
    .dispatch('post/uploadPostImage', file)
    .then((response) => {
      console.log('Succes : Upload file')
    })
    .catch(() => {
      console.log('Error')
    })
},

我的服务:

上传文件(客户端,文件){ console.log(文件)

  return client
     .mutate({
        mutation: uploadFile,
        variables: {
           file,
        },
        fetchPolicy: 'no-cache',
     })
     .then(({ data }) => {
        return data.uploadFile
     })
     .catch((error) => {
        throw new Error(error.message)
     })
  },

}

我的 uploadFile 突变:

const uploadFile = gql`
    mutation($file: Upload) {
    uploadFile(file: $file) {
        filename
        mimetype
        encoding
   }
 }
`

在 API 上,在架构中

type Mutation {
    # Upload
    uploadFile(file: Upload!): File!
}

type File {
    filename: String!
    mimetype: String!
    encoding: String!
}

我使用 apollo-server-express

您需要安装客户端依赖项,然后更新您的客户端createUploadLink而不是HttpLink

npm install apollo-upload-client

要连接它,我们需要将HttpLink Link 实例替换为使用 apollo-upload-client 的createUploadLink工厂 function 创建的 Link。

参考: https://www.apollographql.com/blog/graphql/file-uploads/with-react-hooks-typescript-amazon-s3-tutorial/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM