Reputation: 79
I have some files stored in Windows Azure blob container (let's say file1.txt and file2.txt). In an ASP.NET MVC4 application (hosted on azurewebsites) I need to create a "download as zip" link. When user clicks it, he gets a zip file containing both txt files. I'm having hard time writing controller method for accomplishing this task :-( Can someone please provide short example? Thanks a lot.
Upvotes: 1
Views: 1821
Reputation: 17182
Here goes some code. Code is in raw format, please enhance it as per your usage. I used DotNetZip and Table Storage Nugets.
Code to generate Zip -
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.
}
Code for download 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 utilities helper class -
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";
}
}
}
Upvotes: 6