Issue uploading image to Contentful through lambda function

Hello!
I’m a big-time Netlify fan but this is my first time here at the support forum. I facing some issue with using Netlify Functions and don’t really have any clue on what to do now.

What I’m trying to do
I’m creating a Gatsby website with Contentful as it’s the data source. I have a form on the site that users can submit with some data. Every time a user submits the form, I call a Netlify Function from the front-end which then calls the Contentful API to add the submitted data as a new entry in the CMS. I can’t do this directly from the front-end because of CORS issue and the API URL includes API key, which I don’t want to be publically accessible.
All this works great. Now, I need to allow my user to upload an image through the form.

Issues I’m facing
I implemented the image upload flow according to Contentful’s documentation here:

This involves making a POST request with Content-Type: application/octet-stream. The complete flow for the form submission, after adding image upload looks something like this:

  1. Front-end calls Netlify Function with the image file
  2. Netlify Function makes an API request to Contentful with the image
  3. Contentful saves the image in its media storage and returns an id for the file
  4. Netlify Function returns this id to Front-end
  5. The front-end makes another call to Netlify function, with other form data and the image id it just received
  6. Netlify function calls the Contentful API again to add an entry in the CMS with the form data and associates the image with the entry using the image’s id.

These too works perfectly when I run the function locally using the netlify-lambda serve functions command. But once I deployed it on Netlify, everything still worked but the images I upload shows up as corrupt files in Contentful.

I’m very confused about why this might happen. It’s the exact same code between my local and deployed site, so I’m not sure what can I change that could make any difference.

Any help with it is highly appreciated. Thanks for your time! :slight_smile:

@faahim01, the lambda function has a runtime limit of 10 seconds. I suspect that your file fails to stream completely when the function stops running. When using netlify-lambda, there is no such runtime limit, which could explain the difference. Could you try a much smaller file and see if things work? You might need to explore a different approach if you expect to upload larger files.

1 Like