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

早过忘川 提交于 2020-01-16 18:17:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/53885186/python-django-fails-at-decoding-file-encoded-as-base64-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!