Python file.save 保存空文件

问题描述 投票:0回答:1

我从前端上传检索文件,并以这种方式转换文件的哈希值:

blob_file = convert_to_blob(file)

有了这个功能:

def convert_to_blob(file: file_storage.FileStorage) -> bytes:
    os_path = os.path.join(config('UPLOAD_CONVERT'), "convert.pdf")
    file.save(os_path)
    # Convert digital data to binary format
    with open(os_path, 'rb') as file:
        blobData = file.read()
    return blobData

这工作正常并且文件按预期保存。 之后,我第二次保存文件,但将哈希值作为文件目标文件夹中的名称:

   if file and allowed_file(file.filename):
        # first, convert the file as blob, so we can build a hash over the blob
        blob_file = convert_to_blob(file)
        hash_ = hashlib.md5(blob_file).hexdigest()

        # save file local
        file_path = f"{config('UPLOAD_FOLDER')}/{request.form['mandant']}"
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        os_path = os.path.join(f"{file_path}/{hash_}.pdf")
        file.save(os_path)

但由于某种原因,文件第二次无法正确保存。 它总是空的。 我尝试过将文件保存在不同的文件夹中,并且之前没有构建哈希的东西,但没有成功。

有人可以解释一下这里发生了什么吗?

python file
1个回答
0
投票

要解决此问题,您可以在读取文件后添加“

file.seek(0)
”以将文件指针重置到开头。

© www.soinside.com 2019 - 2024. All rights reserved.