Home > database >  Invalid base64-encoded string: number of data characters cannot be 1 more than a multiple of 4
Invalid base64-encoded string: number of data characters cannot be 1 more than a multiple of 4

Time:01-19

I am currently developing a web application with classic js in frontend and Flask (with python then) in backend.

I get ever this error when I upload a image in base64 to flask app.

Invalid base64-encoded string: number of data characters (403869) cannot be 1 more than a multiple of 4

here my codes in frontend:

var base64Data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAIAAAC6s0uzAAAgAElEQVR4nOy9yZIkOZIl JgZENHNNveIzOyiaaK5DVH1rY z/N58Q//J9MfMYYiasjK...'
var imgData64 = base64Data.substr(base64Data.indexOf(',')   1);
                    
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        //...;
    }
};
xhttp.open("POST", "http://127.0.0.1:5000/upload", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`img=${imgData64}`);

and backend:

@app.route('/upload', methods = ['POST', 'GET'])
def index():
    if request.method == 'POST':
        img_data = request.form['img']
        img_data  = '=' * (-len(img_data) % 4)
        with open("imageToSave.png", "wb") as fh:
            fh.write(base64.decodebytes(img_data.encode()))

CodePudding user response:

That's a very common misunderstanding. The string

var base64Data = 'data:image/png;base64,iVBORw0KGgo...'

is not a Base64 string, but a DataURL

URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents

that contains a Base64 string. The Base64 string starts directly after 'base64,'. Therefore you need to cut of the 'data:image/png;base64,' part.

CodePudding user response:

As mentioned by @jps; you can split your data with base64, text:

base64Data.split('base64,')[1:][0]

you will get something like:

'iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAIAAAC6s0uzAAAgAElEQVR4nOy9yZIkOZIl JgZENHNNveIzOyiaaK5DVH1rY z/N58Q//J9MfMYYiasjK...'
  • Related