title: How to save base64 image in python flask server
body: <p>I try to save a base64 image string that comes from HTTP post request and for some reason, I get multiple different errors</p>
  
  <blockquote>
    <p>binascii.Error: Incorrect padding</p>
  </blockquote>
  
  <p>Also, i look at this StackOverflow question but is not working
  <a href="https://stackoverflow.com/questions/2323128/convert-string-in-base64-to-image-and-save-on-filesystem-in-python/2324133">Convert string in base64 to image and save on filesystem in Python</a></p>
  
  <p>but in the end, I get a png file that is 0 bytes</p>
  
  <p>My question is how I can save a base64 string image on my server filesystem</p>
  
  <h3>I get this error</h3>
  
  <blockquote>
    <p>return binascii.a2b_base64(s)</p>
  </blockquote>
  
  <h3>What I get is this format from the client side:</h3>
  
  <blockquote>
    <p>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC.....AgICgoKC/vuJ91GM9en4hT/AI3TLT8PoqYVw//Z</p>
  </blockquote>
  
  <h3>From the client side I send this request</h3>
  
  <pre><code>{
        "img" : "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wCEAAICAgICAgMCAgMFAwMDBQYFBQUFBggGBgYGBggKCAgIC.....AgICgoKC/vuJ91GM9en4hT/AI3TLT8PoqYVw//Z"
  }
  </code></pre>
  
  <h3>in my python code, I have this method to read and save the base64 image</h3>
  
  <pre><code>@app.route('/upload', methods=['POST']) 
  def upload_base64_file(): 
      """ 
          Upload image with base64 format and get car make model and year 
          response 
      """
  
    data = request.get_json()
    # print(data)
  
    if data is None:
        print("No valid request body, json missing!")
        return jsonify({'error': 'No valid request body, json missing!'})
    else:
  
        img_data = data['img']
  
        # this method convert and save the base64 string to image
        convert_and_save(img_data)
  
  
  
  
  def convert_and_save(b64_string):
  
      b64_string += '=' * (-len(b64_string) % 4)  # restore stripped '='s
  
      string = b'{b64_string}'
  
      with open("tmp/imageToSave.png", "wb") as fh:
          fh.write(base64.decodebytes(string))
  </code></pre>