简体   繁体   English

更改 Azure 存储 Blob 中文件的内容类型

[英]Change Content Type for files in Azure Storage Blob

I use only Microsoft Azure Storage and no other Azure products/services.我只使用 Microsoft Azure 存储,不使用其他 Azure 产品/服务。 I upload files to my storage blob via ftp type client (GoodSync), and I need to change the content type of all the files based on their file extension after they are already in the Blob.我通过 ftp 类型客户端 (GoodSync) 将文件上传到我的存储 Blob,并且我需要在所有文件已经在 Blob 中之后根据它们的文件扩展名更改它们的内容类型。 I have looked around and have not found out how to do this without having one of their VPS with PowerShell.我环顾四周,没有找到如何在没有使用 PowerShell 的 VPS 的情况下执行此操作。 What are my options and how do I accomplish this?我有哪些选择以及如何实现? I really need step by step here.我真的需要一步一步来这里。

I recently had the same issue so I created a simple utility class in order to "fix" content type based on file's extension.我最近遇到了同样的问题,所以我创建了一个简单的实用程序类,以便根据文件的扩展名“修复”内容类型。 You can read details here您可以在此处阅读详细信息

What you need to do is parse each file in your Azure Storage Containers and update ContentType based on a dictionary that defines which MIME type is appropriate for each file extension.您需要做的是解析 Azure 存储容器中的每个文件,并根据定义适合每个文件扩展名的 MIME 类型的字典更新 ContentType。

// Connect to your storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

// Load Container with the specified name 
private CloudBlobContainer GetCloudBlobContainer(string name)
{
    CloudBlobClient cloudBlobClient = _storageAccount.CreateCloudBlobClient();
    return cloudBlobClient.GetContainerReference(name.ToLowerInvariant());
}
// Parse all files in your container and apply proper ContentType
private void ResetContainer(CloudBlobContainer container)
{
    if (!container.Exists()) return;

    Trace.WriteLine($"Ready to parse {container.Name} container");
    Trace.WriteLine("------------------------------------------------");

    var blobs = container.ListBlobs().ToList();

    var total = blobs.Count;
    var counter = 1;

    foreach (var blob in blobs)
    {
        if (blob is CloudBlobDirectory) continue;

        var cloudBlob = (CloudBlob)blob;

        var extension = Path.GetExtension(cloudBlob.Uri.AbsoluteUri);

        string contentType;
        _contentTypes.TryGetValue(extension, out contentType);
        if (string.IsNullOrEmpty(contentType)) continue;

        Trace.Write($"{counter++} of {total} : {cloudBlob.Name}");
        if (cloudBlob.Properties.ContentType == contentType)
        {
            Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (skipped)");
            continue;
        }

        cloudBlob.Properties.ContentType = contentType;
        cloudBlob.SetProperties();
        Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (reset)");
    }
}

_contentTypes is a dictionary that contains the appropriate MIME type for each file extension: _contentTypes是一个字典,其中包含每个文件扩展名的适当 MIME 类型:

private readonly Dictionary _contentTypes = new Dictionary()
    {
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg" }
    };

Full list of content types and source code can be found here .可以在此处找到内容类型和源代码的完整列表。

Here you are a refreshed version for latest Azure.Storage.Blobs SDK.这是最新 Azure.Storage.Blobs SDK 的更新版本。 I'm using .Net 5 and console app.我正在使用 .Net 5 和控制台应用程序。

using Azure.Storage.Blobs.Models;
using System;
using System.Collections.Generic;
using System.IO;

var contentTypes = new Dictionary<string, string>()
{
    {".woff", "font/woff"},
    {".woff2", "font/woff2" }
};

var cloudBlobClient = new BlobServiceClient("connectionstring");
var cloudBlobContainerClient = cloudBlobClient.GetBlobContainerClient("fonts");
await cloudBlobContainerClient.CreateIfNotExistsAsync();

var blobs = cloudBlobContainerClient.GetBlobsAsync();

await foreach (var blob in blobs)
{
    var extension = Path.GetExtension(blob.Name);

    contentTypes.TryGetValue(extension, out var contentType);
    if (string.IsNullOrEmpty(contentType)) continue;

    if (blob.Properties.ContentType == contentType)
    {
        continue;
    }

    try
    {
        // Get the existing properties
        var blobClient = cloudBlobContainerClient.GetBlobClient(blob.Name);
        var properties = await blobClient.GetPropertiesAsync();

        var headers = new BlobHttpHeaders { ContentType = contentType };

        // Set the blob's properties.
        await blobClient.SetHttpHeadersAsync(headers);
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM