File upload process using fileCreate

Anyone recently tried uploading files to Shopify with the fileCreate mutation?

I went through the process of using stagedUploadMutation first, then uploading the files to the URLs and lastly using the fileCreate mutation but there’s something wrong with uploading the files. If anyone has an example of how they do it I’d love to check it out.

In the meantime, my method is below, if anyone spots something I’m missing I’d love to know what it is.

The error that I get is Bad Request - Invalid multipart request with 0 mime parts

import FormData from 'form-data'
import fs from 'fs'
import path from 'path'
import os from 'os'
...

for (const target of stagedUploadResult.stagedUploadsCreate.stagedTargets) {
  const { url, resourceUrl, parameters } = target
  const fileName = target.resourceUrl.split('/').at(-1)

  const form = new FormData()

  parameters.forEach(({ name, value }) => {
    form.append(name, value)
  })

  const file = fs.createReadStream(path.join(os.tmpdir(), fileName))

  form.append('file', file)

  const response = await fetch(url, {
    method: 'POST',
    headers: {
      ...form.getHeaders(),
    },
    body: form,
  })

  if (!response.ok) {
    const text = await response.text()
    throw new Error(
      `Failed to upload file: ${response.statusText} - ${text}`
    )
  }
}

It’s hard to tell exactly where your issue lies without seeing the full GraphQL that you are trying to send.

I would recommend a couple of things:

  1. Give the .dev assistant a try as it was able to get this one almost fully accurate
  2. Work to get the GraphQL working first before trying to integrate your code that way you can separate out concerns (maybe you did that)

So what I tried on the .dev assistant was " How do I use the filecreate mutation?"

And here is the GraphQL mutation that it gave me

 mutation fileCreate($files: [FileCreateInput!]!) {
     fileCreate(files: $files) {
       files {
         id
         fileStatus
         alt
         createdAt
       }
       userErrors {
         field
         message
       }
     }
   }

And here is the input that I used to the mutation

   {
     "files": [
       {
         "alt": "fallback text for an image",
         "contentType": "IMAGE",
         "originalSource": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0e/Shopify_logo_2018.svg/512px-Shopify_logo_2018.svg.png"
       }
     ]
   }

And that worked. I hope this helps get you moving in the right direction!

1 Like

Thanks @eytan-shopify. I managed to get it working last night. The only issue was, as I described, uploading the files to the given URL from staged uploads, everything else was working properly.

Specifically, the file was not being appended properly, so instead of form.append('file', file) I did form.append('file', file, { filename: fileName }).
Also, for some strange reason fetch was not working so I had to use axios.