簡體   English   中英

Web應用程序從Azure存儲Blob下載到計算機

[英]Web Application download from Azure Storage Blobs to Computer

我試圖通過網絡應用程序從azure下載文件到計算機。 當我在本地運行項目時它可以工作,但是當上傳到ftp服務器時它不會下載。

我試過了Environment.SpecialFolder.Peronal,Desktop等。

public async Task<bool> DownloadBlobAsync(string file, string fileExtension, string directory)
    {

        string downlaodPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        _container = _client.GetContainerReference(containerName);
        _directoy = _container.GetDirectoryReference(directory);

        CloudBlockBlob blockBlob = _directoy.GetBlockBlobReference(file + "." + fileExtension);

        using (var fileStream = File.OpenWrite(downlaodPath +  "/"+ file + "." + fileExtension))
        {
            await blockBlob.DownloadToStreamAsync(fileStream);

            return true;
        }
    }

預期的輸出應該在文檔或桌面上。

您看到的問題是由於您的代碼在Web服務器上執行不是在客戶端(用戶)計算機上執行。

換句話說,當您嘗試保存到Environment.SpecialFolder.Personal ,您嘗試將其保存到Web服務器上的該文件夾,而不是用戶台式計算機。

您需要做的是返回請求中blob的內容,並讓瀏覽器保存文件 - 可能會提示用戶(取決於他們的瀏覽器設置)確切地保存它。 你不應該指定這個。

以下是如何執行此操作的示例:

public async Task<HttpResponseMessage> DownloadBlobAsync(string file, string fileExtension, string directory)
{
    _container = _client.GetContainerReference(containerName);
    _directoy = _container.GetDirectoryReference(directory);

    CloudBlockBlob blockBlob = _directoy.GetBlockBlobReference(file + "." + fileExtension);

    using (var ms = new MemoryStream())
    {
        await blockBlob.DownloadToStreamAsync(ms);

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(ms.ToArray())
        };

        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "somefilename.ext"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue(blockBlob.Properties.ContentType);

        return result;
    }
}

請注意 ,這是低效的,因為它會首先將blob下載到Web服務器,然后將其返回給客戶端。 它應該足以開始。

當瀏覽器觸發此端點時,將提示用戶將文件保存在PC上的某個位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM