将Base64图像上传到S3时出现损坏问题

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

});

我的代码有什么问题?在我的终端中没有错误,我在s3中有文件,但是当我下载它时它是损坏的。


一个以base64编码的图片能否从文件中打开?我一直认为这只适用于内联图片。当您使用文本或十六进制编辑器检查文件时,它是否看起来像base64? - Michael - sqlbot
1
@Michael-sqlbot 您可以设置标题 Content-Encoding=base64:https://dev59.com/n2s05IYBdhLWcg3wANPj#26111627。不确定我们是否能够回答 OP 的问题,因为我们不知道 s3fsImpl 是什么。 - danneu
@danneu https://www.npmjs.com/package/s3fs - Nichole A. Miler
@danneu,我发现上传到S3的文件是base64编码的,因为我在writeFile函数中传递了“base64”参数。 - Nichole A. Miler
1个回答

11

由于我不知道你代码中的s3fsImpl是什么,所以无法回答你的实现方法,但这是我如何使用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
   });

base64Img变量在哪里? - KD.S.T.
1
你是对的,应该是数据而不是base64Img。 - Abdullah Adeeb

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