如何从blob下载文件并发送它有一个文件响应

2024-09-24 02:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个客户端页面,它将列出容器中的所有文件,在选择一个文件时,文件名和容器名一起发送到服务器。 服务器应启动文件下载,并应发送文件作为对客户端请求的响应,请参阅下图:

client download window

我试着用把你的blob峎到流中

@app.route("/blobs/testDownload/")
def testDownload():
  container_name =request.args.get("containerName")
  print(container_name)
  local_file_name= request.args.get("fileName")

  with BytesIO() as input_blob:
     with BytesIO() as output_blob:

    # Download as a stream
        block_blob_service.get_blob_to_stream(container_name, local_file_name, input_blob)
        copyfileobj(input_blob, output_blob)
        newFile = str(output_blob.getvalue())
        with open("file.txt","a") as f:
            f.write(newFile)
            f.close()

return send_file('file.txt',attachment_filename='sample.txt',as_attachment=True,mimetype='text/plain')

但是要下载的文件只有文本文件格式,我想下载的文件不考虑它的格式。我知道这不是通过webapi下载文件的正确方式。在

请给我一个建议


Tags: 文件name服务器txt客户端inputoutputget
2条回答

尝试不要硬编码扩展,因为扩展是blob名称的一部分,无论您从documentation使用哪个方法。当您首先在本地下载文件时,请查看get_blob_to_path方法。本地文件名与blob容器中的文件名相同。在

你可以试着blob.名称对于容器中的每个blob文件。Blob name包含文件扩展名(您只需解析它),您可以将其用作上述方法的参数,,这样您就不必硬编码它了: 下面您可以找到一个示例,说明如何迭代容器中的文件并获取blob名称,您只需根据您的用例调整它

block_blob_service = BlockBlobService(account_name=accountName, account_key=accountKey)

# create container if not exists called 'batches'
container_name ='batches'
block_blob_service.create_container(container_name)

# Set the permission so the blobs are public.
block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container)

# Calculation

blobs = block_blob_service.list_blobs(container_name)

for blob in blobs.items:
    file_name = blob.name

所以现在可以对'/'使用file_name和split方法,最后一项是文件名.扩展名. 在

你使用的是固定文件名“文件.txt“为了所有可能的原因。在这里使用流似乎没用。请改为尝试get_blob_to_path(),检查以下修改后的代码:

-//您的代码//-

block_blob_service.get_blob_to_path(container_name, local_file_name, local_file_name)
# notice that I'm reusing the local_file_name here, hence no input/output blobs are required return send_file(local_file_name,attachment_filename=local_file_name,as_attachment=True,mimetype='text/plain')


完整代码:

@app.route("/blobs/testDownload/")
 def testDownload():
 container_name =request.args.get("containerName")
 print(container_name)
 local_file_name= request.args.get("fileName")

# Download as a file
block_blob_service.get_blob_to_path(container_name, local_file_name, local_file_name)


return send_file(local_file_name,attachment_filename=local_file_name,as_attachment=True,mimetype='text/plain')

看看能不能用!在

相关问题 更多 >