簡體   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