【问题标题】:base64 image corrupted uploading to S3上传到 S3 的 base64 图像损坏
【发布时间】:2016-04-14 13:01:51
【问题描述】:
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 可以设置标题Content-Encoding=base64:stackoverflow.com/a/26111627/511200。不确定我们能否回答 OP 的问题,因为我们不知道 s3fsImpl 是什么。
  • @danneu 我还看到上传到 s3 的文件是 base64,因为我在 writeFile 函数中传递了“base64”。

标签: javascript node.js express amazon-s3


【解决方案1】:

由于我不知道您的代码中的 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 变量在哪里
  • 你是对的,它应该是不是base64Img的数据
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 2020-04-15
  • 2022-08-13
  • 2015-11-14
  • 2018-01-16
  • 2019-05-28
  • 2020-02-11
相关资源
最近更新 更多