0
votes

I am trying to upload an image using direct REST API call using the code below. Code works from my local pc (localhost:3000).

const cloudinaryUrl = 'https://api.cloudinary.com/v1_1/{my_id}/image/upload';
const imageUrl = 'https://{test_image_url}/images/{image}.jpg';

const saveImage = async () => {
  try {
    const fd = new FormData();
    fd.append('file', imageUrl);
    fd.append('upload_preset', 'my_preset');
    fd.append('tags', 'browser_upload');

    const image = await fetch(`${cloudinaryUrl}`, {
      method: 'POST',
      body: fd
    });

    console.log('Response', image);

  } catch (err) {
    console.log('err', err);
  }
};

The image is saved successfully but the response is not correct. The response is below:

   {
     body: "",
     type: "cors",
     bodyUsed: false,
     status: 200,
     statusText: "OK",
     url: "https://api.cloudinary.com/v1_1/{my_id}/image/upload"
   }

Correct response is supposed to be something like this:

{
 public_id: 'sample',
 version: '1312461204',
 width: 864,
 height: 564,
 format: 'jpg',
 created_at: '2017-08-10T09:55:32Z',
 resource_type: 'image',
 tags: [], 
 bytes: 9597, 
 type: 'upload', 
 etag: 'd1ac0ee70a9a36b14887aca7f7211737', 
 url: 'http://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg',
 secure_url: 'https://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg',
 signature: 'abcdefgc024acceb1c1baa8dca46717137fa5ae0c3',
 original_filename: 'sample'
}

If anyone knows how to solve my issue, it would be great.

1
It's a bit hard to tell what might be the issue as the response you get back isn't a Cloudinary response. And you mention that it uploads successfully to Cloudinary, so my first guess would be to investigate what fetch is doing.Daniel Mendoza

1 Answers

0
votes

You can get the response body by calling the promise-based methods https://javascript.info/fetch

For example, you can use the method json() to parse the response as JSON.

const image = await fetch(url, { method: "POST", body: formData });
const result = await image.json();
console.log('Response', result);