Python/Django无法解码由javascript编码为base64的文件 [英] Python / Django fails at decoding file encoded as base64 by 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);
});
};
被此呼叫的人:
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
});
}
};
整个字段变量都发布到django服务器上,到目前为止没有问题.
And the whole fields variable gets posted to a django server, no issues so far.
在python django端:
On the python django end:
str_encoded = request.data["file"]
str_decoded = base64.b64decode(str_encoded)
第二行返回错误binascii.Error: Invalid base64-encoded string: length cannot be 1 more than a multiple of 4
.我已经在Google上搜索并阅读到这可能是一个填充问题,但是我不知道如何解决它.
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.
推荐答案
您将不得不从javascript
添加的前缀中删除base64
字符串.
前缀有点像data:{type};base64,{actual-base64-string-follows}
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}
在php中,我遇到了同样的问题,我测试了字符串是否以"data:"
前缀开头,并从字符串的开头剥离到;
(分号)的位置再加上8个字符(以捕获最后的字符) ; base64,").
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,").
然后,您可以使用python解码剩余的base64
字符串,因为它现在是有效的base64
字符串.
Then you can use python to decode the base64
string remaining as it is now a valid base64
string.
这篇关于Python/Django无法解码由javascript编码为base64的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!