【问题标题】:Base64 encode file while uploading in flask [duplicate]在烧瓶中上传时Base64编码文件[重复]
【发布时间】:2019-06-21 05:56:30
【问题描述】:

你知道烧瓶中文件的base64编码吗?

我试过了……

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

我有错误 #FileNotFoundError: [Errno 2] 没有这样的文件或目录:'Tulips.jpg'

有什么想法吗?提前谢谢你?

https://pastebin.com/nGubkfeY

【问题讨论】:

  • 也许this 会有所帮助
  • 不一样。

标签: python python-3.x flask base64


【解决方案1】:

无需致电open。 Flask 已经为你提供了一个可读的文件流。

另外,请注意 b64encode 返回 bytes 而不是 str

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

PS:在选择变量名的时候尽量避免built-in identifiers比如str。它可以为您省去一些麻烦。

【讨论】:

    【解决方案2】:

    当您使用相对文件路径(即简单地传递Tulips.jpg)打开文件时,文件的路径是相对于当前工作目录计算的。如果文件不存在——你会得到一个错误。在您的情况下进行调试的简单方法是在应用程序启动时或在使用os.getcwd() 打开文件之前打印当前工作目录,并检查文件是否实际上位于/your/working/dir/Tulips.jpg

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2016-10-23
      • 1970-01-01
      • 2021-07-03
      相关资源
      最近更新 更多