Upload Image To Shopify Via API

Upload Image To Shopify Via API

Ido1425
Shopify Partner
26 0 0

Hello everyone!

I am facing an issue uploading image buffers to Shopify files through my app.

the process is working but in the Shopify files dashboard, there is a processing error on all images.

The error:

צילום מסך 2024-07-09 ב-18.34.16.png

This is the code for the process(this is gadget.dev platform app):

 

async function uploadImage(productId, imageId, compressedBuffer, imageFormatTemp, connections, logger) {
  try {
    // Step 1: Create the image asset in Shopify using stagedUploadsCreate mutation
    const uploadQuery = `
      mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
        stagedUploadsCreate(input: $input) {
          stagedTargets {
            url
            resourceUrl
            parameters {
              name
              value
            }
          }
        }
      }
    `;

    const uploadVariables = {
      input: [
        {
          filename: `${imageId}-compressed.${imageFormatTemp}`,
          mimeType: `image/${imageFormatTemp}`,
          httpMethod: "POST",
          resource: "FILE",
          fileSize: `${compressedBuffer.length}`
        },
      ],
    };

    const uploadResponse = await graphqlWithRetry(uploadQuery, uploadVariables, connections, logger);
    const stagedTarget = uploadResponse.stagedUploadsCreate.stagedTargets[0];
    const { url, parameters } = stagedTarget;

    // Step 2: Upload the compressed image to the pre-signed URL
    const formData = new FormData();
    parameters.forEach(param => formData.append(param.name, param.value));
    formData.append('file', compressedBuffer, `${imageId}-test.${imageFormatTemp}`);
    await fetch(url, {
      method: 'POST',
      body: formData,
      headers: {
        ...formData.getHeaders(), // Pass the headers generated by FormData library
      },
    });

    // Step 3: Create the image asset in Shopify using fileCreate mutation
    const createFileQuery = `
      mutation fileCreate($files: [FileCreateInput!]!) {
        fileCreate(files: $files) {
          files {
            id
            alt
            createdAt
          }
        }
      }
    `;

    const createFileVariables = {
      files: [
        {
          alt: "test upload Image",
          contentType: "IMAGE",
          originalSource: stagedTarget.resourceUrl,
        },
      ],
    };

    await graphqlWithRetry(createFileQuery, createFileVariables, connections, logger);
    logger.info('New compressed image created');
  } catch (error) {
    logger.error(error, `Failed to update image ${imageId} for product ${productId} in Shopify.`);
  }
}

all the process seems to work well on my side, I get the 'New compressed image created' log, but in Shopify, I keep getting the error with extra info with the error.

Replies 3 (3)

chintannyalwani
Shopify Partner
18 4 3

Hi @Ido1425

what are you getting in stagedTarget.resourceUrl variable ?

 

make sure you are using the absolute url of the image not the image from the file input

in shopify file upload mutation only allows the originalSource value to be absolute url (https://{{your image from the server}}).

 

If my assistance was helpful to you, please consider liking and marking it as a solution to facilitate easy access for others.

Thank you

Need help in Theme customization? Chat on WhatsApp.



Store Customization | Feature Enhancement | Shopify Development Service
Ido1425
Shopify Partner
26 0 0

hi, thanks for the response.

stagedTarget.resourceUrl is the resource Url i got as a response to the stagedUploadsCreate mutation, as i understood this is the url i need to pass to the fileCreate mutation.

Ido1425
Shopify Partner
26 0 0

Anyone?

no info on shopify docs at all