繁体   English   中英

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

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

我正在使用它作为对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);
    });
  };

哪个被这样调用:

  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服务器,到目前为止没有问题。

在python django端:

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上搜索并阅读到这可能是一个填充问题,但是我不知道如何解决它。

您将必须从javascript添加的前缀中删除base64字符串。 前缀就像data:{type};base64,{actual-base64-string-follows}一样data:{type};base64,{actual-base64-string-follows}

在php中,我遇到了同样的问题,我测试了字符串是否以"data:"前缀开头,并且将其从字符串开头剥离到;的位置; (分号)加上8个字符(以捕获最后的“; base64”)。

然后,您可以使用python解码剩余的base64字符串,因为它现在是有效的base64字符串。

暂无
暂无

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

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