python兼容js base64,Python / Django无法解码由javascript编码为base64的文件

I'm using this, in react, to base64 encode an image file:

fileToBase64 = (filename, filepath) => {

return new Promise(resolve => {

var file = new File([filename], filepath);

var reader = new FileReader();

reader.onload = function(event) {

resolve(event.target.result);

};

reader.readAsDataURL(file);

});

};

Which gets called by this:

handleChangeFile = event => {

const { name, files } = event.target;

if (files.length) {

const file = files[0];

let fields = this.state.fields;

this.fileToBase64(file).then(result => {

fields[name].value = result;

});

fields[name].isFilled = true;

this.setState({

fields: fields

});

}

};

And the whole fields variable gets posted to a django server, no issues so far.

On the python django end:

str_encoded = request.data["file"]

str_decoded = base64.b64decode(str_encoded)

The second line returns an error that binascii.Error: Invalid base64-encoded string: length cannot be 1 more than a multiple of 4. I've googled and read that this is probably a padding issue, but I don't know how to fix it.

解决方案

You will have to strip the base64 string from the prefix added by javascript.

The prefix is sth like data:{type};base64,{actual-base64-string-follows}

In php, where I had same issue, I tested if string starts with "data:" prefix and I strip it from start of string up to the position of the ; (semicolon) plus 8 characters (to catch the final ";base64,").

Then you can use python to decode the base64 string remaining as it is now a valid base64 string.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值