如何将Azure blob文件下载到下载文件夹中而不是在浏览器中

时间:2020-04-12 07:17:51

标签: azure azure-blob-storage azure-sas

我想在页面中放置一个按钮,当用户单击该按钮时,我想将azure blob下载到下载文件夹中。

  1. 我生成Blob链接网址:

    var downloadLink = blobService.getUrl('mycontainer','myblob','SAS_TOKEN');

  2. 获得此网址后,我将使用以下解决方案进行下载:

    var link = document.createElement("a");
    link.download = name;
    link.href = url;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

我在S3中使用了相同的文件,可以在同一浏览器中将文件下载到下载文件夹中,但是对于Azure,当我使用此解决方案时,它只是打开一个新选项卡并在浏览器中显示内容。

有人可以帮忙看看为什么吗?如何下载文件而不是在浏览器中显示内容?

生成的网址是:

https://myBucket.blob.core.windows.net/mycontainer/1000/rawEvents.json?se=2022-04-20T23%3A59%3A59Z&sp=rwdlacup&sv=2018-03-28&ss=b&srt=sco&sig=EzsjwqKfYmwwUo2n1ySkCBAsTfW35ic8M8F6tfuXEPo%3D

如果单击此URL,它也可以读取内容。

1 个答案:

答案 0 :(得分:2)

您需要确保Content-TypeContent-Disposition标头具有触发浏览器下载文件的值。内容分配尤其重要。

Content-Type: application/octet-stream
Content-Disposition: attachment

您可以设置内容处置on the blob itself

        var blob = container.GetBlobReference(userFileName);
        blob.Properties.ContentDisposition = "attachment";
        blob.SetProperties();

add it to your SAS token(另请参见相应的blog post)。

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("videos");
        string userFileName = service.FirstName + service.LastName + "Video.mp4";
        CloudBlockBlob blob = container.GetBlockBlobReference(userFileName);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
        {
            Permissions = SharedAccessBlobPermissions.Read,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
        };
        SharedAccessBlobHeaders blobHeaders = new SharedAccessBlobHeaders()
        {
            ContentDisposition = "attachment; filename=" + userFileName
        };
        string sasToken = blob.GetSharedAccessSignature(policy, blobHeaders);
        var sasUrl = blob.Uri.AbsoluteUri + sasToken;//This is the URL you will use. It will force the user to download the video.