简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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