4
router.post('/image', multipartMiddleware , function(req, res) {

   var file_name = req.body.name;
   var data = req.body.data;

   return s3fsImpl.writeFile(file_name , data , 'base64').then(function (err) { 

        res.status(200).end();
    });

});

What's wrong in my code above? There's no error in my therminal, I have the file in my s3 but it's corrupted when I download it.

Nichole A. Miler
  • 1,281
  • 2
  • 11
  • 21
  • Can an image encoded in base64 be opened from a file? I always assumed that only worked for inline images. When you examine the file with a text or hex editor, does it look like base64? – Michael - sqlbot Jan 10 '16 at 01:47
  • 1
    @Michael-sqlbot You can set the header `Content-Encoding=base64`: http://stackoverflow.com/a/26111627/511200. Not sure we can answer OP's question since we have no idea what `s3fsImpl` is. – danneu Jan 10 '16 at 02:08
  • @danneu https://www.npmjs.com/package/s3fs – Nichole A. Miler Jan 10 '16 at 09:27
  • @danneu Also I'm seeing the file which been uploaded to s3 is base64 since I pass 'base64' in the writeFile function. – Nichole A. Miler Jan 10 '16 at 09:27

1 Answers1

11

Since I don't know what s3fsImpl is in your code, I can't answer this to your implementation but here's how I would do it using aws-sdk:

const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const file_name = req.body.name;
const data = req.body.data;
// We need to get the format of the file from the base64 string i.e. data:image/png;base64<base64String>
const format = data.substring(data.indexOf('data:')+5, data.indexOf(';base64'));

// We need to get the actual file data from the string without the base64 prefix
const base64String = data.replace(/^data:image\/\w+;base64,/, '');
const buff = new Buffer(base64String,'base64');

s3.upload({
    Bucket:'s3-bucket-name',
    Key: file_name, 
    Body: buff, 
    ContentEncoding:'base64',
    ContentType:format
}, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data);           // successful response
   });
Abdullah Adeeb
  • 3,826
  • 1
  • 16
  • 14