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

Question:

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()))
Asked By: NobodyKnowsAboutMe

||

Answers:

I solved a problem, using a different approach.
I’ve changed a bit code in frontend (js) and backend (flask – python).

The problem is XMLHttpRequest, I still don’t exactly why, but instead of this I’ve used ajax() method of jQuery version 3.

$.ajax({
    type: "POST",
    url: "/upload",
    data: {
        img: imgData64
    }
});

and the backend is:

@app.route('/upload', methods = ['POST', 'GET'])
def upload():
    if request.method == 'POST':
        img = request.form['img']
        img_data = img.split(',')[1]
        with open("imageToSave.jpg", "wb") as fh:
            fh.write(base64.decodebytes(img_data.encode()))

Afterall, the reason if it wasn’t worked the old approach is maybe the parameter of setRequestHeader() of XMLHttpRequest.

Anyway I recommend you using jQuery, it’s cleaner and short.

Answered By: NobodyKnowsAboutMe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.