-1

Have you any idea base64 encode of file in flask?

I have tried ...

import base64


@users_blueprint.route('/add-source', methods=['GET', 'POST'])
@ensure_authenticated
@user_authenticated

def add_user_resource():
    file = request.files['file']

    #file = request.files['file'].filename

    with open(file, "rb") as imageFile:
        str = base64.b64encode(imageFile.read())
        print str  
    return str

I got error #FileNotFoundError: [Errno 2] No such file or directory: 'Tulips.jpg'

any idea? Thank you in advance?

https://pastebin.com/nGubkfeY

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
CodeLove
  • 462
  • 4
  • 14

2 Answers2

2

No need to call open. Flask already provides you with a readable file stream.

Also, note that b64encode returns bytes and not str.

file = request.files['file']
rv = base64.b64encode(file.read())  # bytes
rv = rv.decode('ascii')  # str
return rv

PS: When choosing variable names, try to avoid built-in identifiers such as str. It can save you some trouble.

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
laika
  • 1,319
  • 2
  • 10
  • 16
0

When you open a file with a relative file path (i.e. simply passing Tulips.jpg) a path to a file is calculated relatively to the current working directory. If a file is not there — you'll get an error. Easy way to debug in your case is to print current working dir on app startup or right before file opening with os.getcwd() and check if file actually at /your/working/dir/Tulips.jpg.

Fine
  • 2,114
  • 1
  • 12
  • 18