upload json file from app backend to the files page by the new file api

Avi_Ben_Zaken
Excursionist
14 0 4

Hey,

I need to upload a JSON file which created in the backend part of my app.

1) So I'm using stagedUploadsCreate to get the temp URL for uploading the file to- that part seems to working fine.

2) Then upload the file using fetch - here I think there is a problem, although I'm getting a 201 response with status "created".

When I try using form.append('file', fs.createReadStream(data)); I'm getting 412 precondition failed error.

3) The last step is calling the fileCreate mutation- here there is some issue, although I'm getting a 200 response but no new file URL in the result.

This is my code: 

async function addFileOS2(shopName, accessToken, data) {
    try {
        data = JSON.stringify(data.data);
        const query = JSON.stringify({
            query: `mutation {
        stagedUploadsCreate(
            input:{
            resource: FILE
            filename: "test.json"
            mimeType: "JSON"
            httpMethod: POST
        }
            ) 
            {
                stagedTargets {
                    resourceUrl
                    url
                    parameters {
                      name
                      value
                    }
                  }
                  userErrors {
                    field
                    message
                  }
            }
        }`
        });

        let response = await fetch(`https://${shopName}/admin/api/2021-07/graphql.json`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                "X-Shopify-Access-Token": accessToken,
                'Access-Control-Allow-Origin': '*'
            },
            body: query
        })

        const responseJson = await response.json();
        const { url, parameters, resourceUrl } = responseJson.data.stagedUploadsCreate.stagedTargets[0];
        var FormData = require('form-data');
        var fs = require('fs');

        var form = new FormData();
        parameters.forEach(({ name, value }) => {
            form.append(name, value)
        })
		
        form.append('file', data);//fs.createReadStream(data));

        const response2 = await axios(url, {
            headers: {
                'Content-Length': data.length,
            },
            method: 'POST',
            body: form,
        })

        query = JSON.stringify({
            query: `mutation {
        fileCreate(
            files:{
            originalSource: "${response2.headers.get('location')/*resourceUrl*/}" //tried also using resourceUrl  
        }) {
            files {
              alt
              createdAt
            }
            userErrors {
              code
              field
              message
            }
          }
        }
    }`
        });

        response = await fetch(`https://${shopName}/admin/api/2021-07/graphql.json`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                "X-Shopify-Access-Token": accessToken,
                'Access-Control-Allow-Origin': '*'
            },
            body: query
        })
        if (!response.ok) {
            throw ('File could not be uploaded.')
        }
        console.log(response);
    }
    catch (err) {
        scriptLogger.error('deleteFile failed', { err: `${err}` });
    }
}

 

If you have any suggestions, I would be happy to hear about,

Thanks

0 Likes
GrahamS
Shopify Staff
Shopify Staff
122 18 21

Hey @Avi_Ben_Zaken ,

Can I ask you to provide an x-request-id for this interaction? Your code looks good at a glance, so I'd like to see what is happening here on our side.

Best,

Graham

Graham S | API Support @ Shopify
- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution
- To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

0 Likes