如何在Python中将图像文件作为二进制上传到Azure存储帐户

huangapple go评论68阅读模式
英文:

how to upload image file as binary to azure storage account in python

问题

我有以下代码,目前无法上传从客户端接收的图像文件。它将图像文件作为UploadFile实例接收。我已经阅读到使用read()方法将文件转换为字节,然后我将能够上传,但这对我来说不起作用。不确定我在这里做错了什么。

async def resolve_fileUpload(_, info, file):
    print(f"File - {type(file)}")

    container_client = blob_service_client.get_container_client(
        '4160000000')
    if not container_client.exists():
        container_client.create_container()

    with open(file, "rb") as file:
        result = container_client.upload_blob(
            name='avatar', data=file.read())
    return {
        "status": 200,
        "error": "",
        "fileUrl": "www.test.com"
    }

任何帮助都将不胜感激,因为我现在被卡住了好几天。

英文:

I have this code below which as of now does not upload image file that it receives from the client. It receives the image file as an UploadFile instance. I have read that using the read() method will convert the file to bytes and that way I will be able to upload, but that didn't work for me. Not sure that what I am doing wrong here.

async def resolve_fileUpload(_, info, file):
    print(f"File - {type(file)}")

    container_client = blob_service_client.get_container_client(
        '4160000000')
    if not container_client.exists():
        container_client.create_container()

    with open(file, "rb") as file:
        result = container_client.upload_blob(
            name='avatar', data=file.read())
    return {
        "status": 200,
        "error": "",
        "fileUrl": "www.test.com"
    }

Any help is greatly appreciated as I am stuck on this for days now.

答案1

得分: 2

I tried in my environment and got the below results.
你可以按照下面的代码来实现将图像上传到Azure Blob存储的目标。
demo.py

from fastapi import FastAPI, File, UploadFile
from azure.storage.blob import BlobServiceClient
from io import BytesIO

app = FastAPI()

# Initialize Azure Storage Blob Service Client
connection_string = "your-connection-string"
blob_service_client = BlobServiceClient.from_connection_string(connection_string)

@app.post("/upload")
async def resolve_fileUpload(file: UploadFile = File(...)):
    print(f"File - {type(file)}")

    container_client = blob_service_client.get_container_client('test')
    if not container_client.exists():
        container_client.create_container()

    file_bytes = await file.read()  # Read the file content as bytes

    with BytesIO(file_bytes) as byte_stream:
        result = container_client.upload_blob(name='avatar/avatar.jpg', data=byte_stream)

    return {
        "status": 200,
        "error": "",
        "fileUrl": "www.test.com"
    }

使用pip install uvicorn安装uvicorn。

使用以下命令在终端中运行上述文件:uvicorn <yourpythonfilename>:app --reload

一旦你在终端中执行以上命令,你将获得如下结果。

如何在Python中将图像文件作为二进制上传到Azure存储帐户

现在,创建另一个名为test.py的Python文件,其中包含以下代码:

import requests

url = "http://127.0.0.1:8000/upload"
files = {'file': open('path/to/file.jpg', 'rb')}
response = requests.post(url, files=files)
print(response.status_code, response.text)

输出:

如何在Python中将图像文件作为二进制上传到Azure存储帐户

Portal:

如何在Python中将图像文件作为二进制上传到Azure存储帐户

英文:

I tried in my environment and got the below results.

You can follow the below code to achieve your goal to upload images to Azure blob storage.

demo.py

from fastapi import FastAPI, File, UploadFile
from azure.storage.blob import BlobServiceClient
from io import BytesIO

app = FastAPI()

# Initialize Azure Storage Blob Service Client
connection_string = &quot;your-connection-string&quot;
blob_service_client = BlobServiceClient.from_connection_string(connection_string)

@app.post(&quot;/upload&quot;)
async def resolve_fileUpload(file: UploadFile = File(...)):
    print(f&quot;File - {type(file)}&quot;)

    container_client = blob_service_client.get_container_client(&#39;test&#39;)
    if not container_client.exists():
        container_client.create_container()

    file_bytes = await file.read()  # Read the file content as bytes

    with BytesIO(file_bytes) as byte_stream:
        result = container_client.upload_blob(name=&#39;avatar/avatar.jpg&#39;, data=byte_stream)

    return {
        &quot;status&quot;: 200,
        &quot;error&quot;: &quot;&quot;,
        &quot;fileUrl&quot;: &quot;www.test.com&quot;
    }

Install uvicorn using pip install uvicorn

Run the above file using uvicorn &lt;yourpythonfilename&gt;:app --reload

Once you execute with above command in your terminal you will get like below.

如何在Python中将图像文件作为二进制上传到Azure存储帐户

Now, create another python file test.py with the below code:

    import requests
    
    url = &quot;http://127.0.0.1:8000/upload&quot;
    files = {&#39;file&#39;: open(&#39;path/to/file.jpg&#39;, &#39;rb&#39;)}
    response = requests.post(url, files=files)
    print(response.status_code, response.text)

Output:

如何在Python中将图像文件作为二进制上传到Azure存储帐户

Portal:

如何在Python中将图像文件作为二进制上传到Azure存储帐户

答案2

得分: 0

MS Docs显示upload_blob需要一个文件I/O对象,而不是实际的字节。来自: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-upload-python#upload-a-block-blob-from-a-local-file-path

尝试将代码更改为仅传递Reader对象,而不是数据。

with open(file, "rb") as file:
    result = container_client.upload_blob(
        name='avatar', data=file)
英文:

MS Docs indicate that upload_blob needs a file I/O object, not the actual bytes. From: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-upload-python#upload-a-block-blob-from-a-local-file-path

Try changing your code to just pass the Reader object, instead of the data.

with open(file, &quot;rb&quot;) as file:
    result = container_client.upload_blob(
        name=&#39;avatar&#39;, data=file)

huangapple
  • 本文由 发表于 2023年6月9日 06:14:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定