React native backend only accepts file://

Good day,

I am follow the react native course and making sure that it will work on web browsers.

I am getting 400 bad request from backend. Error is “images” not allowed

The browser is sending base64 images that causes the error.

IOS and android sending file:// which is accepted by the backend.

I already tried adding base64 to false but still not working on web

const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        base64: false,
        quality: 0.5,
      });

Here is the code that calls the API

const addListing = (listing, onUploadProgress) => {
  const data = new FormData();
  data.append("title", listing.title);
  data.append("price", listing.price);
  data.append("categoryId", listing.category.value);
  data.append("description", listing.description);
  listing.images.forEach((image, index) => {
    data.append("images", {
      name: "image" + index,
      type: "image/jpeg",
      uri: image,
    });
  });

  // if (listing.location)
  //   data.append("location", JSON.stringify(listing.location));
  return client.post(endpoint, data, {
    onUploadProgress: (progress) =>
      onUploadProgress(progress.loaded / progress.total),
  });
};

Please help me fix the problem. Do I need to update the backend provided by the lesson?

Already fixed this problem.

looping listings.images return dataURL in web browsers.

need to convert it to blob using this function

function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(",")[1]);

  // separate out the mime component
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}

Detecting platform during post, adding a different approach when “web”

if (Platform.OS === "web") {
    listing.images.forEach((image, index) => {
      let blob = dataURItoBlob(image);
      data.append("images", blob);
    });
  } else {
    listing.images.forEach((image, index) => {
      data.append("images", {
        name: "image" + index,
        type: "image/jpeg",
        uri: image,
      });
    });
  }