JavaScriptプログラムに関する各種メモ書き

base64からFileオブジェクトに変換 / URL(https://xxxxxxxxxxx) から Fileオブジェクトに変換する

● base64 から File オブジェクトに変換する

function dataURLtoFile(dataurl: string, filename: string) {
  const arr = dataurl.split(",");
  if (arr.length === 1) return;

  const result = arr[0].match(/:(.*?);/);
  const mime = result ? result[1] : "application/octet-stream";
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

使い方

const base64 = "xxxxxxxxxxxxxx";
const resizedFile2 = dataURLtoFile(base64, "myfile,jpg");

● URL(https://xxxxxxxxxxx) から Fileオブジェクトに変換する

    /**
     * get random strings
     * 
     * @returns {string} 
     **/
    const getRandString = () => {
      const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
      let rand_str = '';
      for (var i = 0; i < 8; i++) {
        rand_str += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return rand_str;
    }

    /**
     * URL to FileObject
     * 
     * @param   {string}    url 
     * @returns {Promise<File> | Promise<null>}
     **/
    const urlToFile = async (url) => {
      const fileName = url.match(".+/(.+?)([\?#;].*)?$")[1];
      const rndString = getRandString();
      const getFile = await fetch(`${url}?${rndString}`)
        .then((response) => {
          if (!response.ok) {
            console.error('ファイル取得エラー');
            console.error(response);
          }
          else {
            return response.blob()
          }
        })
        .then((blob) => {
          if (blob === undefined) {
            return null;
          }

          return new File([blob], fileName)
        })

      return getFile
    }

● 使い方

(async 関数の中から使用します)

const url_1 = 'https://xxxxxxxx.jpg'
const file_1 = await urlToFile(url_1)

console.log( file_1 );
No.2234
01/31 13:41

edit