简体   繁体   English

Python / Django无法解码由javascript编码为base64的文件

[英]Python / Django fails at decoding file encoded as base64 by javascript

I'm using this, in react, to base64 encode an image file: 我正在使用它作为对base64编码图像文件的响应:

  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. 整个字段变量都已发布到django服务器,到目前为止没有问题。

On the python django end: 在python django端:

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 . 第二行返回一个错误,该错误为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. 我已经在Google上搜索并阅读到这可能是一个填充问题,但是我不知道如何解决它。

You will have to strip the base64 string from the prefix added by javascript . 您将必须从javascript添加的前缀中删除base64字符串。 The prefix is sth like data:{type};base64,{actual-base64-string-follows} 前缀就像data:{type};base64,{actual-base64-string-follows}一样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 ; 在php中,我遇到了同样的问题,我测试了字符串是否以"data:"前缀开头,并且将其从字符串开头剥离到;的位置; (semicolon) plus 8 characters (to catch the final ";base64,"). (分号)加上8个字符(以捕获最后的“; base64”)。

Then you can use python to decode the base64 string remaining as it is now a valid base64 string. 然后,您可以使用python解码剩余的base64字符串,因为它现在是有效的base64字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM