【发布时间】:2014-08-10 08:11:36
【问题描述】:
我一直在使用 Azure Blob 存储服务来保存/恢复要在 Azure 网页中托管的网页上下文中的文件。
在学习过程中,我提出了两种解决方案;第一个基本上使用DownloadToStream,它的作用相同,但使用FileStream。在这种情况下,我必须先将文件写入服务器,然后再将其返回给用户。
public static Stream GetFileContent(string fileName, HttpContextBase context)
{
CloudBlobContainer container = GetBlobContainer();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
Stream fileStream = new FileStream(
context.Server.MapPath("~/App_Data/files/" + fileName), FileMode.Create);
blockBlob.DownloadToStream(fileStream);
fileStream.Close();
return File.OpenRead(context.Server.MapPath("~/App_Data/files/" + fileName));
}
public ActionResult Download(string fileName)
{
byte[] fileContent = MyFileContext.GetFileContent(fileName);
return File(fileContent, "application/zip", fileName);
}
另一方面,我使用 DownloadToByteArray 函数将 Blob 的内容写入以 Blob 文件大小初始化的字节数组中。
public static byte[] GetFileContent(string fileName)
{
CloudBlobContainer container = GetBlobContainer();
CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
blockBlob.FetchAttributes();
long fileByteLength = blockBlob.Properties.Length;
byte[] fileContent = new byte[fileByteLength];
for (int i = 0; i < fileByteLength; i++)
{
fileContent[i] = 0x20;
}
blockBlob.DownloadToByteArray(fileContent,0);
return fileContent;
}
public ActionResult Download(string fileName)
{
byte[] fileContent = MyFileContext.GetFileStream(fileName);
return File(fileContent, "application/zip", fileName);
}
当我查看这两个选项时,我发现第一个选项需要在服务器磁盘中创建一个文件,而第二个选项将 Blob 中的数据存储在一个字节数组中消耗内存。在我的特殊情况下,我将处理 ~150 MB 的文件大小。
鉴于情况(环境、文件大小...),您认为哪种方法最好?
【问题讨论】:
-
您的目标是始终下载用户计算机上的文件吗?或者换句话说,您是想在将这些数据流式传输到用户浏览器之前对其进行处理,还是直接从 Azure 存储下载用户计算机上的文件?
-
只是为了不忽略某些东西:
DownloadToStream需要Stream但FileStream并不是唯一的流类型。 -
@GauravMantri 是的,这个想法只是下载文件而不对其执行任何操作。
-
查看这个类似的问题:stackoverflow.com/questions/6752000/… 给出了一种解决方案,即文件直接发送到响应输出流而无需中间保存到磁盘。或者,如果 blob 是公开的并且您的业务逻辑允许,您可以随时提供指向该 blob 的直接 http 链接。
-
@Julen
fileContent[i] = 0x20;背后的原因是什么?