簡體   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