Upload Image from Nodejs using fetch

I’m trying do a very basic upload to Cloudflare Images from Nodejs (my backend server). I receive the file from frontend, and I’m guessing I’m just not doing the correct conversion. I apologize, this is probably a pretty elementary question, I’m just not well versed in file i/o

I’m getting a Buffer from the frontend. When I log the typeof of it, I get object. The buffer string looks like this when logged:

<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 0a 00 00 01 79 08 02 00 00 00 71 fd 95 f0 00 00 00 19 74 45 58 74 53 6f 66 74 77 61 72 65 00 ... 1916 more bytes>

I’ve tried every possible conversion I can come across and put it in the fetch request:

const headers = {
          Authorization: `Bearer ${cloudflareToken}`,
          'content-type': 'image/jpeg',
        }

        try {
          const imageResponse = await fetch(
            cloudflareURL,
            {
              method: 'POST',
              headers,
              body: file,
            },
          )

          console.log(imageResponse)

Where file is the Buffer string.

In return I get a 415 error Unsupported Media Type. So I’m probably not converting or sending the file correctly. Any ideas?

Hi, you are trying to upload a file as an image. API accepts only multipart/form-data content type.

https://api.cloudflare.com/#cloudflare-images-upload-an-image-using-a-single-http-request

Reason:
aside image data itself a request can consist other auxiliary data, like: metadata or requireSignedURLs.

Maybe this will help you construct requests properly: node.js - NodeJS Request how to send multipart/form-data POST request - Stack Overflow

1 Like