简体   繁体   中英

How to decode Base64 string and upload as image on to amazon s3 in nodejs?

I tried like this, its producing an image everytime with same name, i want dynamic name and it must be uploaded to amazon s3. please help

let base64String = req.body.imgBase64;
      let base64Image = base64String.split(';base64,').pop();
      fs.writeFile('image.jpg', base64Image, { encoding: 'base64' }, function(
        err
      ) {
        console.log('File created');
        res.json('fire created');
      });

This snippet will always name the image 'image.jpg' because you are passing that as a constant into the fs.writeFile() first parameter. To dynamically name files, you will need to include a variable within your loop that changes at each iteration. For example, you can do this with an integer:

var i;
var count = 0;
for (i = 0; i < numfiles; i++) {
  let base64String = req.body.imgBase64;
  let base64Image = base64String.split(';base64,').pop();
  var countString = String(count)
  fs.writeFile('image' + countString + '.jpg', base64Image, { encoding: 'base64' }, function(
        err
      ) {
        console.log('File ' + countString + ' created');
        res.json('File ' + countString + ' created');
      });
  count++;
}

As for uploading to S3, there are many sources online to guide you on uploading to S3 using node.js.

I would recommend adding a timestamp/datestamp to your image to make it simple. As for the amazon thing, I would recommend asking as a separate question because that's completely different.

let base64String = req.body.imgBase64;
      let base64Image = base64String.split(';base64,').pop();
      fs.writeFile(`image${Date.now()}.jpg`, base64Image, { encoding: 'base64' }, function(
        err
      ) {
        console.log('File created');
        res.json('fire created');
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM