Shopify App Image File Upload Through GraphQL API – Processing Error

Shopify App Image File Upload Through GraphQL API – Processing Error


0

I’m working on a shopify app using node js and react with graphql.

Here is what I’m trying to achieve, the client when using my Shopify app has a dropzone where he can upload images, I’m trying to save those images to the files in his store, I keep getting the processor error when I check the files dashboard of the store.

I read somewhere that there needs to be a third step between the stagedUploadsCreate mutation and the fileCreate mutation, which is to prepare a form and commence uploading!
Here are the resources I checked:
Link1
Link2
Link3
I have tried it but it never works for me at all.

The staged response does indeed return a url and paameters but that’s the last successful step that happens.

Here is my client side code:
The following is supposed to communicate with the server the image file the client is uploading.

Here is the code in the server side:

app.post('/api/upload-endpoint', async (req, res) => {
  try {
    if (!req.files || !req.files.file) {
      return res.status(400).json({ error: 'No file uploaded' });
    }

    const uploadedFile = req.files.file;
    const formData = new FormData();
    // Define the stagedUploadsCreate mutation input
    const input = [
      {
        resource: 'IMAGE',
        httpMethod: 'POST',
        mimeType: uploadedFile.mimetype,
        filename: uploadedFile.name,
        fileSize: uploadedFile.size.toString(),
      },
    ];
  
    // Create a staged upload URL using stagedUploadsCreate mutation
    let stagedUploadResponse = await fetchUploadImageFile(res.locals.shopify.session, input);

    const stagedTarget = stagedUploadResponse.body.data.stagedUploadsCreate.stagedTargets[0];
//passing the parameters
    stagedTarget.parameters.forEach(({name, value}) =>
     {
      formData.append(name, value);
    });

//Passing the file as argument (should be last), I tried to pass only the file instead but that didn't change anything.
    formData.append('file', uploadedFile.data, {
      filename: uploadedFile.name,
      contentType: uploadedFile.mimetype,
    });

    // Now, we upload the file
    const fileCreateResponse = await fetch(stagedTarget.url, {
      method: 'POST',
      body: formData,
    });
  
      let myArrayOfFiles = new Array();
      const paramObj =
    {
        "alt": "Image Alt!",
        "originalSource": stagedTarget.resourceUrl,
        "contentType": "IMAGE",
    };
    myArrayOfFiles.push(paramObj);
   
 
    const myResultIs2 = await fetchUploadImageFileContinue(res.locals.shopify.session, myArrayOfFiles);


  } catch (error) {
    console.error('Error handling file upload:', error);
    res.status(500).json({ error: 'An error occurred' });
  }


});
const formData = new FormData();
  formData.append('file', filesArray.current[0]);

  const response = await fetch2('/api/upload-endpoint', {
    method: 'POST',
    body: formData,
  });
 export default async function fetchUploadImageFile(
    session, myArr
  ) {
    const client = new shopify.api.clients.Graphql({ session });
    try {
  const myData = await client.query({
    data: {
      "query": `mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
        stagedUploadsCreate(input: $input) {
          stagedTargets {
            url
            resourceUrl
            parameters {
              name
              value
            }
          }
        }
      }`,
      "variables": 
      {
        "input": myArr
      },
    },
  });

  return myData;

    } catch (error) {
      if (error instanceof GraphqlQueryError) {
        throw new Error(
          `${error.message}n${JSON.stringify(error.response, null, 2)}`
        );
      } else {
        throw error;
      }
    }

  }
 export default async function fetchUploadImageFileContinue(
    session, filesArray
  ) {
    const client = new shopify.api.clients.Graphql({ session });
    try {
  const myData = await client.query({
    data: {
      "query": `mutation fileCreate($files: [FileCreateInput!]!) {
        fileCreate(files: $files) {
          files {
            alt
            createdAt
          }
        }
      }`,
      "variables": {
        "files": filesArray
      },
    },
  });

  return myData;
     
    } catch (error) {
      if (error instanceof GraphqlQueryError) {
        throw new Error(
          `${error.message}n${JSON.stringify(error.response, null, 2)}`
        );
      } else {
        throw error;
      }
    }

  }
  

Share
Improve this question


Load 3 more related questions


Show fewer related questions

0

Reset to default



Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *