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}`
)
}
}
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.