【问题标题】:Octet Stream to PDF Azure Python八位字节流到 PDF Azure Python
【发布时间】:2020-06-03 13:35:58
【问题描述】:

我正在尝试将 PDF 上传到 Azure blob 存储,然后下载并阅读它。上传工作正常,当我在 Azure 存储资源管理器中打开它时,文件打开正常。但是,当我尝试下载它时,我得到一个八位字节流,我不知道如何将它转换回 PDF。我通过函数应用程序完成这一切,所以我不确定将所有内容写入临时文件是否会有所帮助。我试过了,我得到了一个损坏的 pdf 作为我的输出。我的代码如下。

上传:

blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'

file = req.files['file']
try:
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=file.filename)
    blob_client.upload_blob(file)
except Exception as e:
    print(e)
    return "Unspecified Error"

下载:

blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = 'testblobstore123'
file = req.form['file']
blob_client = blob_service_client.get_blob_client(container=container_name, blob=file)
# data = blob_service_client.get_data_to_text(container_name, file)

data = blob_client.download_blob().readall()

【问题讨论】:

    标签: python-3.x pdf azure-functions azure-blob-storage


    【解决方案1】:

    首先在我的测试中,我打开文件链接或下载到本地,内容类型是八位字节流,但是他们能够读取。

    下面是我的下载代码。

    blob_service_client = BlobServiceClient.from_connection_string(connect_str)
    container_name = 'test'
    blob_name='nodejschinese.pdf'
    download_file_path = os.path.join('D:', blob_name)
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
    
    with open(download_file_path, "wb") as download_file:
        download_file.write(blob_client.download_blob().readall())
    

    其次,如果您想在上传时更改内容类型,可以在upload_blob方法中添加ContentSettings

    下面是我的上传代码ContentSettings

    from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient,ContentSettings
    
    connect_str='connection string'
    blob_service_client = BlobServiceClient.from_connection_string(connect_str)
    container_name = 'test'
    local_file_name='nodejs.pdf'
    upload_file_path='E:\\nodejs.pdf'
    
    blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)
    with open(upload_file_path, "rb") as data:
        blob_client.upload_blob(data,content_settings=ContentSettings(content_type='application/pdf'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2016-09-27
      • 2020-04-09
      相关资源
      最近更新 更多