How do I upload a file from browser to Strapi with GraphQL?

System Information
  • Strapi Version: v3.6.7
  • Operating System:
  • Database:
  • Node Version: v14.17.5
  • NPM Version:
  • Yarn Version:

Hello !

I’m trying to submit some fields and an image. Permissions has been set to public for this content type.

Here is my function to upload (using GitHub - prisma-labs/graphql-request: Minimal GraphQL client supporting Node and browsers for scripts)

async function submitFanContent({ author, link, image }: SubmitFanContentArgs) {
  const CREATE_FAN_CONTENT = gql`
    mutation submitFanContent($author: String!, $link: String!, $image: Upload!) {
      createFanContent(input: { data: {
        author: $author,
        link: $link,
        image: $image
      }}) {
        fanContent {
          author
          link
          image {
            url
          }
        }
      }
    }
  `

  return client.request(CREATE_FAN_CONTENT, {
    author,
    link,
    image
  })
}

Here is the call of the function :

const data = await submitFanContent({
 author: form.author, // string
 link: form.link, // string
 image: form.image, // This is equal to event.target.files[0]
});

I am getting this error :

{
  "errors": [
    {
      "message": "Variable \"$image\" of type \"Upload!\" used in position expecting type \"ID\".",
      "locations": [
        {
          "line": 2,
          "column": 65
        },
        {
          "line": 6,
          "column": 16
        }
      ],
      "extensions": {
        "code": "GRAPHQL_VALIDATION_FAILED"
      }
    }
  ]
}

Any help appreciated, thank you!

1 Like

Hello @KeziahMoselle ,

I’ve started strapi a week ago.

I was also getting this type of error message and I resolved this issue.

As per the error message, the image attribute expects only “ID”.

ID you will get from the Media Library ASSET ID.

for Example

so means you can’t upload the image from here.
for image uploading, you need to call the UPLOAD_FILE mutation.

Use Altair for File upload because default GQL playground doesnt support that

mutation SingleImageUpload($refId: ID, $ref: String, $field: String, $info: FileInfoInput, $file: Upload!) {
   upload(refId: $refId, ref: $ref, field: $field, file: $file, info: $info) {
     data {
       id
       attributes {
         name   
         createdAt
         updatedAt
       }
     }
   }
}
{
  "refId": "2",
  "ref": "api::physical-exchanger.physical-exchanger",
  "field": "photo",
  "info": {
      "name":"test",
      "alternativeText": "",
      "caption": "`"
  }
}

“refId”: “ID_OF_YOUR_ENTRY_IN_YOUR_COLLECTION_TYPE”,

“ref”: “YOUR_COLLECTION_TYPE_NAME”,

“field”: “FIELD_NAME”