Node.js基于64位编码的图像解码和写入文件

19
我正在将这个Flex表单的内容(不要问为什么)发送到node。有一个名为"photo"的post参数,它是一个base64编码的图像。
照片的内容被成功地发送过去了。问题是当我尝试解码并将它们写入文件时出现了问题。
  var fs = require("fs");

  fs.writeFile("arghhhh.jpg", new Buffer(request.body.photo, "base64").toString(), function(err) {});

我也尝试过使用toString("binary")。但是似乎node.js并没有解码所有的内容,它似乎只解码了jpg文件头信息,剩余部分未被解码。

请问是否有人可以帮助我解决这个问题?

谢谢。


这里的照片是什么??是base64图像吗?? - R J.
4个回答

29
尝试完全删除.toString()并直接编写缓冲区。

我感觉非常愚蠢。Nathan,你是一个英雄。谢谢你。 - Mehdi

12

这是我的完整解决方案,它可以读取任何base64图像格式,对其进行解码,并将其以正确的格式保存在数据库中:

    // Save base64 image to disk
    try
    {
        // Decoding base-64 image
        // Source: https://dev59.com/KWIj5IYBdhLWcg3wb0rX
        function decodeBase64Image(dataString) 
        {
          var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
          var response = {};

          if (matches.length !== 3) 
          {
            return new Error('Invalid input string');
          }

          response.type = matches[1];
          response.data = new Buffer(matches[2], 'base64');

          return response;
        }

        // Regular expression for image type:
        // This regular image extracts the "jpeg" from "image/jpeg"
        var imageTypeRegularExpression      = /\/(.*?)$/;      

        // Generate random string
        var crypto                          = require('crypto');
        var seed                            = crypto.randomBytes(20);
        var uniqueSHA1String                = crypto
                                               .createHash('sha1')
                                                .update(seed)
                                                 .digest('hex');

        var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';

        var imageBuffer                      = decodeBase64Image(base64Data);
        var userUploadedFeedMessagesLocation = '../img/upload/feed/';

        var uniqueRandomImageName            = 'image-' + uniqueSHA1String;
        // This variable is actually an array which has 5 values,
        // The [1] value is the real image extension
        var imageTypeDetected                = imageBuffer
                                                .type
                                                 .match(imageTypeRegularExpression);

        var userUploadedImagePath            = userUploadedFeedMessagesLocation + 
                                               uniqueRandomImageName +
                                               '.' + 
                                               imageTypeDetected[1];

        // Save decoded binary image to disk
        try
        {
        require('fs').writeFile(userUploadedImagePath, imageBuffer.data,  
                                function() 
                                {
                                  console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
                                });
        }
        catch(error)
        {
            console.log('ERROR:', error);
        }

    }
    catch(error)
    {
        console.log('ERROR:', error);
    }

这就是我正在寻找的答案,谢谢。 - Joniras

2

在nodejs 8.11.3中,new Buffer(string, encoding)已被弃用,现在的替代方式是Buffer.from(string, encoding),不需要加上.toString()

更多细节请参阅nodejs文档:Buffer


0

移除 .toString()

在这里,您将base64解码为缓冲区,这很好,但然后您将缓冲区转换为字符串。这意味着它是一个字符串对象,其代码点是缓冲区的字节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接