2014-01-06 64 views
1

我有一些文件存儲在Windows Azure blob容器(讓我們說file1.txt和file2.txt)。 在一個ASP.NET MVC4應用程序(託管在azurewebsites)中,我需要創建一個「作爲zip下載」鏈接。當用戶點擊它時,他會得到一個包含兩個txt文件的zip文件。 我有很難寫入控制器方法完成這一任務:-(是否有人可以提供簡單的例子? 感謝。Windows Azure blob壓縮併發送到客戶端(ASP.NET MVC)

回答

6

這裏去一些代碼。代碼以原始格式,請加強它按你的用法 我用DotNetZip和表存儲Nugets

代碼,以生成郵編 -

using (ZipFile zip = new ZipFile()) 
    using(MemoryStream stream = new MemoryStream()) 
    { 
     BlobRepository rep = new BlobRepository(); 

     // Download files from Blob storage 
     byte[] b = rep.DownloadFileFromBlob(filename); 

     zip.AddEntry("sample1", b); 
     //add as many files as you want 

     zip.Save(stream); 
     // use that stream for your usage. 
    } 

代碼下載BLOB -

public byte[] DownloadFileFromBlob(string filename) 
{ 
    // Get Blob Container 
    CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference(BlobUtilities.FileContainer); 
    // Get reference to blob (binary content) 
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename); 
    // Read content 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     blockBlob.DownloadToStream(ms); 
     return ms.ToArray(); 
    } 
} 

Blob實用程序助手類 -

internal class BlobUtilities 
{ 
    public static CloudBlobClient GetBlobClient 
    { 
     get 
     { 
      CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection string here"); 
      CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 
      return blobClient; 
     } 
    } 
    public static string FileContainer 
    { 
     get 
     { 
      return "container name here"; 
     } 
    } 
} 
+0

謝謝了很多,這對我非常有幫助。 –