上传一个base64连接codeD映像的Node.js服务器无法正常工作 [英] Uploading a base64 encoded image to Node.js server not working

查看:211
本文介绍了上传一个base64连接codeD映像的Node.js服务器无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MEAN.io,我试图上传一个base64连接codeD映像。

客户端,AngularJS:

  //图片我们要送出来
          VAR base64Image =文件[I]          var文件= {
            图片:base64Image,
            类型:类型,
            文件类型:延伸,
            或CharacterId:character._id
          };          VAR NEWFILE =新MediaSendBase64(文件);          NEWFILE。$保存(功能(图像){
            如果(!图片){
              的console.log(错误IMAGE');
            }
            其他{
              的console.log('成功');              的console.log(图片);
            }
          });

服务器端的NodeJS,控制器:

  app.use(bodyParser.json({限制:'50MB'}));
app.use(bodyParser.urlen codeD({限制:'50MB',延伸:真正}));exports.uploadBase64 =功能(REQ,资源,下一个){  VAR uploadPath = path.normalize(process.cwd()+'/包/字/公/资产/上传/'),
      数据=新的缓冲区(''),
      imgUrl的=不确定,公众// URL来显示图片
      类型=不确定;
  //万一'/上传directoy不存在
  如果(!fs.existsSync(uploadPath)){
    fs.mkdirSync(uploadPath,0755);
  }
  //解码的base64形象
  VAR数据=新的缓冲区(req.body.image的base64');  //创建该文件的名称 - > +或CharacterId类型+时间戳+分机
  变种文件名= req.body.characterId +' - '+ req.body.type +' - '+新的Date()的getTime()的toString()+。'。 + req.body.filetype;  //编写图像文件系统的
  fs.writeFile(uploadPath +文件名,数据功能(错误){    如果(ERR){
      的console.log(ERR);
      返回res.status(500)以.json({
        错误:不能上传图片。抱歉。'
      });
    }    的console.log('保存在HD');    的console.log('整理');    //发送成功响应
    res.json({
      imgUrl的:imgUrl的,
      型:
    });  });};

问题是存储在/上传不工作的文件。我看不到图像。所述的base64图像被发送和文件写入到硬盘,但它不可能将其打开。

有什么不对?任何建议?

谢谢!


解决方案

这也许是您要保存元数据文件。因此,从无效的base64使得德codeD数据。

下面是我的意思是:

 数据:图像/ PNG; BASE64,iVBORw0KG ....

中的数据:图像/ PNG; Base64是刚刚元,不带使用Base64因此codeD:

您需要剥离,从刺痛,然后去code,然后保存到磁盘。

我用这个方便的功能:

 函数去codeBase64Image(dataString){
  VAR匹配= dataString.match(/ ^数据:([A-ZA-Z - + \\ /] +);的base64,(+)$ /)
    响应= {};  如果(matches.length!== 3){
    返回新错误(无效输入字符串')​​;
  }  response.type =比赛[1];
  response.data =新缓冲液(比赛[2],'的base64');  返回响应;
}


  

来源:写的NodeJS的base64图像文件


所以从我如何使用它剪断:

  VAR德codedImg =去codeBase64Image(imgB64Data);
 VAR ImageBuffer的德= codedImg.data;
 VAR类型=去codedImg.type;
 变种延长= mime.extension(类型);
 变种文件名=形象。 +扩展;
 尝试{
       fs.writeFileSync(TMP /上传/+文件名,ImageBuffer的,'UTF8');
    }
 赶上(错误){
    console.error(ERR)
 }

在哪里MIME是伟大的节点哑剧库。 NPM安装哑剧。

I'm using MEAN.io and i'm trying to upload a base64 encoded image.

Client side, 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);
            }
          });

Server side, NodeJS, controller:

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
    });

  });

};

The thing is the file stored in /uploads isn't work. I can't see the image. The base64 image is sent and the file is written to hard disk, but it is not possible to open it.

What's wrong? Any suggestion?

Thanks!

解决方案

It maybe that you are trying to save the file with the metadata. hence making the decoded data from base64 invalid.

Here is what I mean:

data:image/png;base64,iVBORw0KG....

The data:image/png;base64 is just meta and is not encoded using base64 so:

You need to strip that from the sting then decode then save to disk.

I use this handy function:

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;
}

source: NodeJS write base64 image-file

So a snip from how I use it:

 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)
 }

Where mime is the great node-mime lib. npm install mime.

这篇关于上传一个base64连接codeD映像的Node.js服务器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆