我需要将我的图像转换为Base64字符串,这样我就可以将我的图像发送到服务器。

有JavaScript文件吗?否则,我如何转换它?


当前回答

如果您使用的是Dojo Toolkit,那么它为我们提供了一种直接编码或解码Base64的方法。

试试这个:

使用dojox.encoding.base64对字节数组进行编码:

var str = dojox.encoding.base64.encode(myByteArray);

解码一个base64编码的字符串:

var bytes = dojox.encoding.base64.decode(str);

其他回答

我发现最安全可靠的方法是使用FileReader()。

演示:映像到Base64

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        var selectedfile = document.getElementById("myinput").files;
        if (selectedfile.length > 0) {
          var imageFile = selectedfile[0];
          var fileReader = new FileReader();
          fileReader.onload = function(fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result;
            var newImage = document.createElement('img');
            newImage.src = srcData;
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>

更新-相同的代码与评论@AnniekJ请求:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
    </div>
    <div>
      <textarea style="width:100%;height:500px;" id="txt">
      </textarea>
    </div>
    <script>
      function encode() {
        // Get the file objects that was selected by the user from myinput - a file picker control
        var selectedfile = document.getElementById("myinput").files;
        // Check that the user actually selected file/s from the "file picker" control
        // Note - selectedfile is an array, hence we check it`s length, when length of the array
        // is bigger than 0 than it means the array containes file objects
        if (selectedfile.length > 0) {
          // Set the first file object inside the array to this variable
          // Note: if multiple files are selected we can itterate on all of the selectedfile array  using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
          var imageFile = selectedfile[0];
          // Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the            user's computer, using File or Blob objects to specify the file or data to read. 
          var fileReader = new FileReader();
          // We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events" 
          fileReader.onload = function(fileLoadedEvent) {
            // AT THIS STAGE THE EVENT WAS RAISED
            // Here we are getting the file contents - basiccaly the base64 mapping
            var srcData = fileLoadedEvent.target.result;
            // We create an image html element dinamically in order to display the image
            var newImage = document.createElement('img');
            // We set the source of the image we created
            newImage.src = srcData;
            // ANOTHER TRICK TO EXTRACT THE BASE64 STRING
            // We set the outer html of the new image to the div element
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            // Then we take the inner html of the div and we have the base64 string
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
          }
          // This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event  
          fileReader.readAsDataURL(imageFile);
        }
      }
    </script>
  </body>
</html>

这个代码片段可以将你的字符串、图像甚至视频文件转换为Base64字符串数据。

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" /> <div id="imgTest"></div> <script type='text/javascript'> function encodeImageFileAsURL() { var filesSelected = document.getElementById("inputFileToLoad").files; if (filesSelected.length > 0) { var fileToLoad = filesSelected[0]; var fileReader = new FileReader(); fileReader.onload = function(fileLoadedEvent) { var srcData = fileLoadedEvent.target.result; // <--- data: base64 var newImage = document.createElement('img'); newImage.src = srcData; document.getElementById("imgTest").innerHTML = newImage.outerHTML; alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML); console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML); } fileReader.readAsDataURL(fileToLoad); } } </script>

需要利用读取器将blob转换为base64,更喜欢使用async-await语法,所以我选择提取读取器逻辑到帮助器,像这样:

//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.readAsDataURL(blob)
  })
}

并在主代码中使用await调用它:

//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
uploadProfile(e) {

    let file = e.target.files[0];
    let reader = new FileReader();

    reader.onloadend = function() {
        console.log('RESULT', reader.result)
    }
    reader.readAsDataURL(file);
}

你可以使用HTML5 <canvas>:

创建一个画布,将图像加载到其中,然后使用toDataURL()来获得Base64表示(实际上,它是一个data: URL,但它包含Base64编码的图像)。