Web应用程序从Azure存储Blob下载到计算机

时间:2019-04-22 21:36:28

标签: c# azure model-view-controller download

我正在尝试通过Web应用程序将文件从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;
        }
    }

预期输出应在文档或桌面上。

1 个答案:

答案 0 :(得分:0)

您看到的问题是由于您的代码正在在网络服务器上执行,而不是在客户端(用户)计算机上执行。

换句话说,当您尝试保存到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上的某个地方。