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

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


当前回答

以下是我所做的:

// Author James Harrington 2014
function base64(file, callback){
  var coolFile = {};
  function readerOnload(e){
    var base64 = btoa(e.target.result);
    coolFile.base64 = base64;
    callback(coolFile)
  };

  var reader = new FileReader();
  reader.onload = readerOnload;

  var file = file[0].files[0];
  coolFile.filetype = file.type;
  coolFile.size = file.size;
  coolFile.filename = file.name;
  reader.readAsBinaryString(file);
}

下面是你如何使用它

base64( $('input[type="file"]'), function(data){
  console.log(data.base64)
})

其他回答

您可以使用FileAPI,但它几乎不受支持。

你可以使用HTML5 <canvas>:

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

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

试试这个:

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

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

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

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

你也可以简单地提取以64为基数的URL的一部分:

var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part

假设您在浏览器中执行此操作:

等待:

import axios from 'axios'

const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);

与承诺

import axios from 'axios'

const response = await axios.get(url, { responseType: 'blob' })
  .then((response) => {
    const dataUrl = window.URL.createObjectURL(response.data);
    // do something with your url
  });