nodejs base64到blob转换

时间:2018-05-31 12:03:23

标签: node.js reactjs blob

我在reactjs(react-webcam)中捕捉网络摄像头截图。屏幕截图采用base64编码字符串的形式。我将base 64string发送到nodejs,我想将base64 String转换为.jpeg文件,这样我就可以保存在Azure Blob存储中。 是否有任何方法可以将base64字符串转换为.jpeg文件。

4 个答案:

答案 0 :(得分:0)

您可以将Base64字符串转换为Buffer,然后尝试将其存储到azure。

var base64String = "....."; // your base64 string
var bufferValue = Buffer.from(base64String,"base64");

答案 1 :(得分:0)

我用过它并且有效。 下面是服务器端代码(NodeJS)

var contentType = 'image/jpeg';
    let base64String=req.body.img;
    let base64Image = base64String.split(';base64,').pop();
    let date=Date.now();
    fs.writeFile(`./uploads/${date}.jpeg`, base64Image, {encoding: 'base64'}, function(err) {
    console.log('File created');
    sourceFilePath= path.resolve(`./uploads/${date}.jpeg`);
   blobName=path.basename(sourceFilePath, path.extname(sourceFilePath));
   //console.log(sourceFilePath);
    blobService.createBlockBlobFromLocalFile(containerName, blobName, sourceFilePath, err => {
            if (err) {
                console.log(err);
            } 
            else {
                //resolve({ message: `Upload of '${blobName}' complete` });
                console.log("UPLOADED")
            }
        });

答案 2 :(得分:-1)

试试这个:

  1. based-blob

    (async function() {
      const b = require('based-blob');
    
      const base64String = 'some base64 data...';
    
      const blob = b.toBlob(base64String);
      const b64s = await b.toBase64(blob);
    
      console.log(b64s == base64String); // true
    })();
    

答案 3 :(得分:-1)

您好我使用此功能

public b64toBlob = (b64Data: string = '', sliceSize?: number) => {
            sliceSize = sliceSize || 512;
            if ( b64Data !== null) {
                let block = b64Data.split(';');
                let dataType = block[0].split(':')[1];
                let realData = block[1].split(',')[1];
                let filename = this.makeid() + '.' + dataType.split('/')[1];
                let byteCharacters = atob(realData);
                let byteArrays = [];
                for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                    let slice = byteCharacters.slice(offset, offset + sliceSize);

                    let byteNumbers = new Array(slice.length);
                    for (let i = 0; i < slice.length; i++) {
                        byteNumbers[i] = slice.charCodeAt(i);
                    }
                    let byteArray = new Uint8Array(byteNumbers);
                    byteArrays.push(byteArray);
                }
                let blob = new Blob(byteArrays, {type: dataType});
                return blob ;
            } else {
                return '';
            }
        }