我正在尝试以CloudBlockBlob的形式从Azure存储中下载文件。我想要允许用户选择下载文件的位置,因此我编写了以下代码来实现这一点
[AllowAnonymous]
public async Task<ActionResult> DownloadFile(string displayName)
{
ApplicationUser user = null;
if (ModelState.IsValid)
{
user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
// Retrieve storage account and blob client.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.AppSettings["StorageConnectionString"]);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(
VisasysNET.Utilities.Constants.ContainerName);
// If the container does not exist, return error.
if (container.Exists())
{
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
if (blob.Name.CompareNoCase(displayName))
{
string contentType = String.Format(
"application/{0}",
Path.GetExtension(displayName).TrimStart('.'));
// No need to dispose, FileStreamResult will do this for us.
Stream stream = new MemoryStream();
await blob.DownloadRangeToStreamAsync(stream, null, null);
return File(stream, contentType, displayName);
}
}
}
return RedirectToAction("Index", "Tools");
}
}
return new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable);
}
这将从Blob存储下载文件,但是当控制器使用FileStreamResult
返回视图时,浏览器会像预期的那样启动保存文件对话框,但文件大小为0字节。 Stream
显示了正确的文件大小,但当我执行...... return File(stream, contentType, displayName);
数据似乎没有传递到保存对话框中。
我该如何使文件正确保存?
感谢您的时间。