设置存储在 Blob 上的媒体文件的内容类型

本文关键字:媒体文件 类型 存储 Blob 设置 | 更新日期: 2023-09-27 18:30:26

我们有一个托管在Azure上的网站。它是基于媒体的,我们使用JWPlayer来播放带有HTTP伪流的媒体。媒体文件以 3 种格式存储在 blob 上 - mp4、ogg、webm。

问题是媒体文件的内容类型设置为所有类型的应用程序/八位字节流。因此,媒体播放和进度条存在一些问题。

如何设置存储在 blob 上的文件的适当内容类型(如 - 视频/mp4、视频/ogg、视频/webm)?

我不想通过进入 blob 接口为每个文件手动执行此操作。一定有其他我不知道的方法可以做到这一点。也许配置文件、设置文件等排序。或者可能是用于为存储在文件夹中的所有文件设置 Content-type 的代码块。

有什么建议吗?谢谢

设置存储在 Blob 上的媒体文件的内容类型

这应该有效:

var storageAccount = CloudStorageAccount.Parse("YOURCONNECTIONSTRING");
var blobClient = storageAccount.CreateCloudBlobClient();
var blobs = blobClient
    .GetContainerReference("thecontainer")
    .ListBlobs(useFlatBlobListing: true)
    .OfType<CloudBlockBlob>();
foreach (var blob in blobs)
{
    if (Path.GetExtension(blob.Uri.AbsoluteUri) == ".mp4")
    {
        blob.Properties.ContentType = "video/mp4";
    }
    // repeat ad nauseam
    blob.SetProperties();
}

或者设置一个字典,这样你就不必写一堆 if 语句。

不幸的是,这里接受的答案目前不适用于最新的 SDK (12.x.+)

使用最新的 SDK,内容类型应通过 BlobHttpHeaders 进行设置。

var blobServiceClient = new BlobServiceClient("YOURCONNECTIONSTRING");
var containerClient = blobServiceClient.GetBlobContainerClient("YOURCONTAINERNAME");
var blob = containerClient.GetBlobClient("YOURFILE.jpg");
var blobHttpHeader = new BlobHttpHeaders { ContentType = "image/jpeg" };
 
var uploadedBlob = await blob.UploadAsync(YOURSTREAM, new BlobUploadOptions { HttpHeaders = blobHttpHeader });

YOURSTREAM可能是new BinaryData(byte[])

下面是使用正确的内容类型将视频上传到 Azure Blob 存储的工作示例:

public static String uploadFile(
     CloudBlobContainer container,String blobname, String fpath) {
    CloudBlockBlob blob;
    try {
        blob = container.getBlockBlobReference(blobname);
        File source = new File(fpath);
        if (blobname.endsWith(".mp4")) {
            System.out.println("Set content-type: video/mp4");
            blob.getProperties().setContentType("video/mp4");
        }
        blob.upload(new FileInputStream(source), source.length());
        return blob.getUri().toString();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (StorageException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

with Azure.Storage.Blogs (12.8.4),我们可以设置文件的内容类型,如下所示。默认情况下,Azure 存储将文件存储在应用程序/八位字节流中,如果是 *.svg 文件,则无法正确呈现在 html 中。因此,在上传到 Blob 时,我们必须将 *.svg 文件类型为 image/svg+xml 的文件保存在 azure blob 存储中。

下面是我开始工作的代码示例。

  BlobServiceClient blobServiceClient = new BlobServiceClient("CONNECTIONSTRING");
  BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("CONTAINERNAME");
  BlobClient blobClient = containerClient.GetBlobClient("BLOBNAME");
  try
  {
    Stream stream = file.OpenReadStream();
    await blobClient.UploadAsync(stream, true);
    blobClient.SetHttpHeaders(new BlobHttpHeaders() { ContentType = file.ContentType });
  }

ContentType Set on header应该放在blobClient.UploadAsync()的正下方。

借助 Azure 存储 v10 SDK,可以使用 BlockBlobURL 上传 Blob,如 Node.js 快速入门中的说明:

const {
  Aborter,
  BlockBlobURL,
  ContainerURL,
  ServiceURL,
  SharedKeyCredential,
  StorageURL,
  uploadFileToBlockBlob
} = require("@azure/storage-blob");
const containerName = "demo";
const blobName = "quickstart.txt";
const content = "hello!";
const credentials = new SharedKeyCredential(
  STORAGE_ACCOUNT_NAME,
  ACCOUNT_ACCESS_KEY
);
const pipeline = StorageURL.newPipeline(credentials);
const serviceURL = new ServiceURL(
  `https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
  pipeline
);
const containerURL = ContainerURL.fromServiceURL(serviceURL, containerName);
const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName);
const aborter = Aborter.timeout(30 * ONE_MINUTE);
await blockBlobURL.upload(aborter, content, content.length);

然后,可以在上传后使用setHTTPHeaders方法设置内容类型:

// Set content type to text/plain
await blockBlobURL.setHTTPHeaders(aborter, { blobContentType: "text/plain" });

可以使用uploadFileToBlockBlob方法从@azure/storage-blob上传文件。

在python中

azure_connection_str = libc.retrieve.get_any_secret('AZURE_STORAGE_CONNECTION')
blob_service_client = BlobServiceClient.from_connection_string(azure_connection_str)
blobs = blob_service_client.list_blobs()
my_content_settings = ContentSettings(content_type='video/mp4')
for blob in blobs:
    blob_client = blob_service_client.container_client.get_blob_client(blob)
    blob_client.set_http_headers(content_settings=my_content_settings)

使用php,可以通过设置内容类型来上传视频,如下所示

$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
//upload
$blob_name = "video.mp4";
$content = fopen("video.mp4", "r");
$options = new CreateBlobOptions();
$options->setBlobContentType("video/mp4");
try {
    //Upload blob
    $blobRestProxy->createBlockBlob("containername", $blob_name, $content, $options);
    echo "success";
} catch(ServiceException $e){
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

这是我所做的

BlobHTTPHeaders h = new BlobHTTPHeaders();
String blobContentType = "image/jpeg";
h.withBlobContentType(blobContentType);
blobURL.upload(Flowable.just(ByteBuffer.wrap(Files.readAllBytes(img.toPath()))), img.length(), h, null, null, null)
.subscribe(resp-> {
  System.out.println("Completed upload request.");
  System.out.println(resp.statusCode());
});
如果你中间

有用于上传文件的API,你可以做这样的事情。

使用 Azure.Storage.Files.Datalake v12.12.1 和数据湖存储第 2 代,您可以使用 DataLakeFileUploadOptions 指定内容类型。

using Azure.Storage.Files
using Microsoft.AspNetCore.StaticFiles;
(...)
public async Task<IActionResult> UploadAsync(string container, string uploadDirectoryPath, 
         IFormFile file) {
     var dataLakeServiceClient = new DataLakeServiceClient(connString);
     var dataLakeFileSystemClient = dataLakeServiceClient.GetFileSystemClient(container);
     var dataLakeFileClient = dataLakeFileSystemClient
                             .GetFileClient(Path.Combine(uploadDirectoryPath, file.FileName));
 
     var fileStream = file.OpenReadStream();
     var mimeType = GetMimeType(file.FileName);
     var uploadOptions = new DataLakeFileUploadOptions()
     {
         HttpHeaders = new PathHttpHeaders() { ContentType = mimeType }                
     };
     await dataLakeFileClient.UploadAsync(fileStream, uploadOptions);
     return Ok();
}
private string GetMimeType(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    if (!provider.TryGetContentType(fileName, out var contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;
}

有关我在此处使用的内容类型和 GetMimeType 方法的更多信息。

可以使用 Azure 存储资源管理器手动执行此操作。 右键单击要更改的文件,然后选择"属性"。转到内容类型并将值编辑为正确的值,即"视频''mp4"