本文介绍了base64图片损坏,无法上传到S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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中有文件,但下载时文件已损坏.
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.
推荐答案
由于我不知道代码中的s3fsImpl
是什么,因此无法对您的实现进行回答,但这是使用aws的方法-sdk:
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
});
这篇关于base64图片损坏,无法上传到S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!