Node.js上传base64图片到腾讯云COS

假如有如下base64格式的图片需要上传到腾讯云COS:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAADGCAYAAACJm/9dAAAGOUlEQVR4Xu3YIatlBRiF4W8UxOQfsBhsgkEFbYIajP4Ck9lk1eIPMEy3WWwGsSlWQQSjCCa72EW5cCfNwPr22cM5wnqmfmvffde7zsvlzIPxDwEEHiPwABMEEHicADF8KhB4AgFi+FggQAyfAQR2BPzF2HGSKiNAjLLB1d0RIMaOk1QZAWKUDa7ujgAxdpykyggQo2xwdXcEiLHjJFVGgBhlg6u7I0CMHSepMgLEKBtc3R0BYuw4SZURIEbZ4OruCBBjx0mqjAAxygZXd0eAGDtOUmUEiFE2uLo7AsTYcZIqI0CMssHV3REgxo6TVBkBYpQNru6OADF2nKTKCBCjbHB1dwSIseMkVUaAGGWDq7sjQIwdJ6kyAsQoG1zdHQFi7DhJlREgRtng6u4IEGPHSaqMADHKBld3R4AYO05SZQSIUTa4ujsCxNhxkiojQIyywdXdESDGjpNUGQFilA2u7o4AMXacpMoIEKNscHV3BIix4yRVRoAYZYOruyNAjB0nqTICxCgbXN0dAWLsOEmVESBG2eDq7ggQY8dJqowAMcoGV3dHgBg7TlJlBIhRNri6OwLE2HGSKiNAjLLB1d0RIMaOk1QZAWKUDa7ujgAxdpykyggQo2xwdXcEiLHjJFVGgBhlg6u7I0CMHSepMgLEKBtc3R0BYuw4SZURIEbZ4OruCBBjx0mqjAAxygZXd0eAGDtOUmUEiFE2uLo7AsTYcZIqI0CMssHV3REgxo6TVBkBYpQNru6OADF2nKTKCBCjbHB1dwSIseMkVUaAGGWDq7sjQIwdJ6kyAsQoG1zdHQFi7DhJlREgRtng6u4IEGPHSaqMADHKBld3R4AYO05SZQSIUTa4ujsCxNhxkiojQIyywdXdESDGjpNUGQFilA2u7o4AMXacpMoIEKNscHV3BIix4yRVRoAYZYOruyNAjB2nW6XemJnfZubvW/0Cre8lxv97+Y9n5sOZeYcc1x2KGNfl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qUTAWIkQu6VBIhRObvSiQAxEiH3SgLEqJxd6UTgP3KtH8dDa+7MAAAAAElFTkSuQmCC

查看一下腾讯云COS接口文档:https://cloud.tencent.com/document/product/436/12264#put-object

cos.putObject({
    Bucket : 'STRING_VALUE',                        /* 必须 */
    Region : 'STRING_VALUE',                        /* 必须 */
    Key : 'STRING_VALUE',                           /* 必须 */
    Body: fs.createReadStream('./a.zip'),           /* 必须 */
    onProgress: function (progressData) {
        console.log(progressData);
    },
}, function(err, data) {
    if(err) {
        console.log(err);
    } else {
        console.log(data);
    }
});

示例代码的Body是传文件流的,那是否支持传Buffer对象呢?再看一下对Body的参数说明:

参数说明上没写是否支持传入Buffer的,那到底支不支持Buffer对象呢?

经过本人亲测,是支持的,只是需要先将base64字符串移除掉前面的“data:image/png;base64,”再转换为Buffer对象即可,代码如下:

//前端传入的base64图片字符串  
var base64img=req.body.img;
//移除“data:image/png;base64,”字符串
var base64Data = base64img.replace(/^data:image\/\w+;base64,/, "");
//转换为Buffer对象
var buffer=Buffer.from(base64Data,'base64');
//开始上传
cos.putObject({
    Bucket : 'STRING_VALUE',                        /* 必须 */
    Region : 'STRING_VALUE',                        /* 必须 */
    Key : 'STRING_VALUE',                           /* 必须 */
    Body: buffer,           /* 必须 */
    onProgress: function (progressData) {
        console.log(progressData);
    },
}, function(err, data) {
    if(err) {
        console.log(err);
    } else {
        //获取刚上传的图片的url
        cos.getObjectUrl({
                    Bucket: config.cos.Bucket,
                    Region: config.cos.Region,
                    Key: key,
                    Sign: false
                }, function (err, data) {
                    if(!err){
                        var url=data.Url
                    }
        });
    }
});

发表评论

电子邮件地址不会被公开。 必填项已用*标注