reactjs FileUpload with GraphQL在尝试上传客户端时将文件显示为无效输入

bnlyeluc  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(79)

我正在尝试使用apollo graphQL上传文件。使用Upload标量和GraphQLUpload,当前客户端失败

类型

export const typeDefs = gql`
  scalar Upload

  type File {
    url: String!
  }

突变和解析器

export const resolvers = {
  Upload: GraphQLUpload

   uploadFile(file: Upload!): File!

    uploadFile: async (_, { file }) => {
      const { createReadStream, filename } = await file;
      const stream = createReadStream();

      const { ext } = path.parse(filename)
      const name = ext + v4()

      const pathName = path.join(__dirname, `../public/images/${name}`)
      await stream.pipe(fs.createWriteStream(pathName))

      return {
        url: `http://localhost:5000/images/${name}`
      };
    },

客户端

export const UPLOAD_FILE = gql`
    mutation UploadFile($file: Upload!){
        uploadFile(file: $file){
            url
        }
    }
`

  const handleUpload = async () => {
    if (!image) return;

    try {
      const { data } = await uploadFile({
        variables: { file: image }
      })
      if (data) {
        console.log('res =>', data)
        handleCreateNewPost(data.uploadFile.url)
      }
    }
    catch (err) {
      console.log(err)
    }

当前我得到一个无效的输入错误:

{"errors":[{"message":"Variable \"$file\" got invalid value { path: \"Photo on 2021-09-07 at 1.34 PM.jpg\" }

image console.logged显示文件对象

File {path: 'Photo on 2021-09-07 at 1.34 PM.jpg', name: 'Photo on 2021-09-07 at 1.34 PM.jpg', lastModified: 1631036079471, lastModifiedDate: Tue Sep 07 2021 13:34:39 GMT-0400 (Eastern Daylight Time), webkitRelativePath: '', …}
path: "Photo on 2021-09-07 at 1.34 PM.jpg"
lastModified: 1631036079471
lastModifiedDate: Tue Sep 07 2021 13:34:39 GMT-0400 (Eastern Daylight Time) {}
name: "Photo on 2021-09-07 at 1.34 PM.jpg"
size: 134828
type: "image/jpeg"
webkitRelativePath: ""
[[Prototype]]: File
gijlo24d

gijlo24d1#

遇到了同样的问题。
问题出在我们的apollo客户端的前端,我们没有在客户端中包含上传链接。

import { createUploadLink } from 'apollo-upload-client'

...

const uploadLink = createUploadLink({ uri: process.env.GATSBY_APOLLO_URL })
  apolloLinks.push(uploadLink)

const client = new ApolloClient({
    link: from(apolloLinks),
    cache: new InMemoryCache(),
  })

还要注意,根据documentation,只能有一个这样的终止链路

Apollo Client can only have 1 terminating Apollo Link that sends the GraphQL requests; 
if one such as HttpLink is already setup, remove it.

因此,如果您的客户端中有这两个链接,您仍然会得到相同的错误。

相关问题