python - 上传到 Azure Blob 存储时自动设置内容类型

标签 python azure upload blob content-type

我正在尝试使用 Python 将数千个文件上传到 Azure 存储。它们的内容类型默认设置为“application/octet-stream”

我知道我可以使用(指定 here )设置单个文件的内容类型:

content_settings = ContentSettings(content_type="something")

但问题是所有文件的内容类型并不相同。我有图像、javascript 文件、html 文件和一百多种其他类型。

在使用 Python 将文件上传到 Azure 存储 blob 之前,如何根据计算机本地的文件自动设置内容类型?

我知道这是可行的,因为azcopy使用正确的内容类型上传。 (我测试过)

这是我编写的Python代码的一部分:

def upload(self, overwrite=False):
    with ThreadPool(self._num_threads) as pool:
        request_processes = []
        for local_path, remote_path in path_generator()
            blob_client = BlobClient.from_blob_url(blob_url=remote_path, credential=credentials)
            file_extension: str = local_path.split('/')[-1].split('.')[-1]
            content_settings = ContentSettings(content_type=file_extension)
            kwargs: Dict[str, Any] = {'blob_type': 'BlockBlob',
                                      'content_settings': content_settings,
                                      'validate_content': True,
                                      'overwrite': overwrite,
                                      'timeout': self._timeout_seconds,
                                      'max_concurrency': 10}
            request_processes.append(pool.apply_async(self._sync_upload_file,
                                                          [blob_client, local_path],
                                                          kwds=kwargs))
            for req in request_processes:
                req.get(self._timeout_seconds)

    @staticmethod
    def _sync_upload_file(blob_client, local_path: str, *args, **kwargs):
        with open(local_path, "rb") as data:
            resp = blob_client.upload_blob(data, *args, **kwargs)
        return resp

此代码的问题在于它使用文件扩展名(js、html、png 等)作为内容类型。例如,html 文件的内容类型应为 text/html

最佳答案

我在这个 website 中找到了一个解决方案.

他们创建了一个从 650 多个文件扩展名到内容类型的映射(字典)。但我仍然有一些文件类型不存在于这本字典中。例如“.map”、“.config”、“.info”等等。

关于python - 上传到 Azure Blob 存储时自动设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72902835/

相关文章:

python - 将接下来的 n 次迭代分配给元组

python - 无法在Python中动态设置文件的权限

asp.net - 在 Azure 中使用 SQL 作为 session 缓存

php - 使用 php 直接写入磁盘

android - java.net.UnknownHostException : graph. facebook.com 问题

python - 如何停止将opencv帧流式传输到浏览器

python - 字典所有键之间的公共(public)项

Azure TCP 分段和 HTTP block

c# - 如何解决Azure “Windows logins are not supported in this version of SQL Server”?

php - CMultiFileUpload 类不在数据库 yii 上插入图像名称