如何使用 Cloudinary 客户端将 Blob URL 转换为 Base64 字符串并检索图像 URL?

How to convert Blob URL to Base64 string and retrieve an Image URL using Cloudinary Client-Side?

我正在使用 React-Dropzone npm 来使用样式精美的拖放开箱即用的文件上传器。我一直坚持这样一个事实,即从 8.2.0 版开始的 React-Dropzone 不包含文件的路径,例如只用图像名称缩短它。然而,他们确实提供了一个 Blob Url。我不知道如何将 Blob-URL 转换为 Base64 字符串,然后将其发送到 Cloudinary。

我想通了:

几个小时后,一些好心人在 Whosebug 上发帖,我拼凑了它。

const getBlobData = (file) => {
    axios({
      method: "get",
      url: file, // blob url eg. blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc
      responseType: "blob",
    }).then(function (response) {
      var reader = new FileReader();
      reader.readAsDataURL(response.data);
      reader.onloadend = function () {
        var base64data = reader.result;
        const formData = new FormData();
        formData.append("file", base64data);
        formData.append("api_key", YOUR_API_KEY);
        // replace this with your upload preset name
        formData.append("upload_preset", YOUR_PRESET_NAME);//via cloudinary
        axios({
          method: "POST",
          url: "https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/upload",
          data: formData,
        })
          .then((res) => {
            const imageURL = res.data.url;
            //YOU CAN SET_STATE HOWEVER YOU WOULD LIKE HERE.
          })
          .catch((err) => {
            console.log(err);
          });
      };
    });
  };

另一种方式可以是:

const url = 'blob:http://uri';

const blobToBase64 = (url) => {
  return new Promise((resolve, _) => {
    // do a request to the blob uri
    const response = await fetch(url);

    // response has a method called .blob() to get the blob file
    const blob = await response.blob();

    // instantiate a file reader
    const fileReader = new FileReader();

    // read the file
    fileReader.readAsDataURL(fileReader);

    fileReader.onloadend = function(){
      resolve(fileReader.result); // Here is the base64 string
    }
  });
};

// now you can get the 
blobToBase64(url)
  .then(base64String => {
    console.log(base64String) // i.e: data:image/jpeg;base64,/9j/4AAQSkZJ..
  });

// or with await/async
const file = await blobToBase64(url);
console.log(file) // i.e: data:image/jpeg;base64,/9j/4AAQSkZJ..