将 Base64 编码的图像上传到 Node.js 服务器不起作用

Rub*_*nez 2 javascript node.js express angularjs mean-stack

我正在使用 MEAN.io,并且正在尝试上传 Base64 编码的图像。

客户端,AngularJS:

          // Image we're going to send it out
          var base64Image = files[i];

          var file = {
            image: base64Image,
            type: type,
            filetype: extension,
            characterId: character._id
          };

          var newFile = new MediaSendBase64(file);

          newFile.$save(function(image) {
            if ( !image ) {
              console.log('ERROR IMAGE');
            }
            else {
              console.log('SUCCESS.');

              console.log(image);
            }
          });
Run Code Online (Sandbox Code Playgroud)

服务器端、NodeJS、控制器:

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

exports.uploadBase64 = function(req, res, next) {

  var uploadPath  = path.normalize(process.cwd() + '/packages/characters/public/assets/uploads/'),
      data        = new Buffer(''),
      imgURL      = undefined,        // public URL to show the pic
      type        = undefined;


  // In case the '/uploads' directoy doesn't exist
  if( !fs.existsSync(uploadPath) ) {
    fs.mkdirSync(uploadPath, 0755);
  }


  // Decoding the base64 image
  var data = new Buffer(req.body.image, 'base64');

  // Creating the name for the file --> characterId + type + timestamp + extension
  var filename = req.body.characterId + '-' + req.body.type + '-' + new Date().getTime().toString() + '.' + req.body.filetype;

  // Writing the image to filesystem
  fs.writeFile(uploadPath + filename, data, function (err) {

    if ( err ) {
      console.log(err);
      return res.status(500).json({
        error: 'Cannot upload the image. Sorry.'
      });
    }

    console.log('SAVED ON HD');

    console.log('FINISHING');

    // Sending success response
    res.json({
      imgURL: imgURL,
      type: type
    });

  });

};
Run Code Online (Sandbox Code Playgroud)

问题是存储在 /uploads 中的文件不起作用。我看不到图像。Base64 图像已发送,文件已写入硬盘,但无法打开它。

怎么了?有什么建议吗?

谢谢!

Joh*_*uys 9

您可能正在尝试使用元数据保存文件。因此使来自 Base64 的解码数据无效。

我的意思是:

data:image/png;base64,iVBORw0KG....
Run Code Online (Sandbox Code Playgroud)

data:image/png;base64 只是元数据,未使用 base64 进行编码,因此:

您需要将其从刺中剥离,然后解码,然后保存到磁盘。

我使用这个方便的功能:

function decodeBase64Image(dataString) {
  var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
    response = {};

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

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

  return response;
}
Run Code Online (Sandbox Code Playgroud)

来源:NodeJS 编写 base64 图像文件

下面是我如何使用它的片段:

 var decodedImg = decodeBase64Image(imgB64Data);
 var imageBuffer = decodedImg.data;
 var type = decodedImg.type;
 var extension = mime.extension(type);
 var fileName =  "image." + extension;
 try{
       fs.writeFileSync(".tmp/uploads/" + fileName, imageBuffer, 'utf8');
    }
 catch(err){
    console.error(err)
 }
Run Code Online (Sandbox Code Playgroud)

其中 mime 是很棒的 Node-Mime 库。npm 安装 mime。