Downloading from Azure Blob storage in C# - c#

I have a very basic but working Azure Blob uploader/downloader built on C# ASP.net.
Except the download portion does not work. This block is called by the webpage and I simply get no response. The uploads are a mixture of images and raw files. I'm looking for the user to get prompted to select a destination and just have the file download to their machine. Can anyone see where I am going wrong?
[HttpPost]
public void DownloadFile(string Name)
{
Uri uri = new Uri(Name);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);
using (Stream outputFile = new FileStream("Downloaded.jpg", FileMode.Create))
{
blob.DownloadToStream(outputFile);

Related

Azure.Storage.Blog downloading file from Azure Storage container to local path - from ASP.NET Core - file path and mime type?

I have an Azure application built with ASP.NET Core using the MVC pattern. Document uploads are stored in Azure Blob Containers and the C# upload code I wrote is working great.
I am using Azure.Storage.Blobs version 12.14.1
Here is my download blob code:
//get document metadata stored in sql table, id comes from a method param
var document = _unitOfWork.Documents.GetById(id);
if (document == null)
{
throw new FileNotFoundException();
}
//get connection and container from appsettings.json
string connection = _appConfig.AzureStorageConnection;
string containerName = _appConfig.AzureStorageContainer;
//work with blob client
var serviceClient = new BlobServiceClient(connection);
var container = serviceClient.GetBlobContainerClient(containerName);
var fileName = document.UniqueDocumentName;
var blobClient = container.GetBlobClient(document.UniqueDocumentName);
using (FileStream fileStream = System.IO.File.OpenWrite("<path>"))
{
blobClient.DownloadTo(fileStream);
}
After I get to using code to set up the file stream, I don't understand what to pass into the OpenWrite method as a path. This application is a B2C app and so how do I just prompt a user to download the file?
I do get a file download with the above code but the file is called download.xml. That is not the file that should be downloaded. I expected the download file to be an .odt file.
Documentation seems to be very sparse on downloading from Azure Blob Storage
EDIT 1.
I got rid of the FileStream and did this instead:
MemoryStream ms = new MemoryStream();
ms.Position = 0;
blobClient.DownloadTo(ms);
return new FileStreamResult(ms, document.FileType);
I did this instead of using FileStream and returned FileResult instead:
MemoryStream ms = new MemoryStream();
ms.Position = 0;
blobClient.DownloadTo(ms);
return new FileStreamResult(ms, document.FileType);

trying to download the word document from azure blob

i am trying to download the word document stored in azure blob container having private access and i need to convert downloaded document into byte array so that i can be able to send to react app
this is the code i am trying below
[Authorize, HttpGet("{id}/{projectphase?}")]
public async Task<ActionResult<DesignProject>> GetDesignProject(string id, string projectphase = null)
{
var blobContainerName = Startup.Configuration["AzureStorage:BlobContainerName"];
var azureStorageConnectionString = Startup.Configuration["AzureStorage:ConnectionString"];
BlobContainerClient blobContainerClient = new BlobContainerClient(azureStorageConnectionString, blobContainerName);
blobContainerClient.CreateIfNotExists();
....... // not sure how to proceed further
.......
......
return new InlineFileContentResult('here i need to return byte array???', "application/docx") { FileDownloadName = fileName };
}
I have got the full path name where the file has been stored like as below
https://xxxx.blob.core.windows.net/design-project-files/99999-99/99999-99-BOD-Concept.docx
and then i have got the file name as well 99999-99-BOD-Concept.docx
Could any one please guide me how to proceed with the next to download the document that would be very grateful to me.
Please try something like the following (untested code though):
public async Task<ActionResult<DesignProject>> GetDesignProject(string id, string projectphase = null)
{
var blobContainerName = Startup.Configuration["AzureStorage:BlobContainerName"];
var azureStorageConnectionString = Startup.Configuration["AzureStorage:ConnectionString"];
BlobContainerClient blobContainerClient = new BlobContainerClient(azureStorageConnectionString, blobContainerName);
blobContainerClient.CreateIfNotExists();
var blobClient = new BlobClient("https://xxxx.blob.core.windows.net/design-project-files/99999-99/99999-99-BOD-Concept.docx");
var blobName = blobClient.Name;
blobClient = new BlobClient(azureStorageConnectionString, blobContainerName, blobName);
using (var ms = new MemoryStream())
{
await blobClient.DownloadToAsync(ms);
return new InlineFileContentResult(ms.ToArray(), "application/docx") { FileDownloadName = fileName };
}
}
Basically what we're doing is that we're first creating a BlobClient using the URL that you have so that we can extract blob's name out of that URL (you can do URL parsing as well). Once we have the blob's name, we create a new instance of BlobClient using connection string, blob container name and blob's name.
Then we download the blob's content as stream and convert that stream to byte array (this part I am not 100% sure that my code would work) and return that byte array.
You don't really need to have this process where your react app requests to your server, so your server downloads the file and then sends it to the react app; that file in blob storage is on the web, downloadable from blob storage so it's kinda unnecessary to hassle your sevrer into being a proxy for it
If you configure public access for blobs then you just put that URL into your react app - user clicks it, bytes download. Happy days. If you have a private container you can still generate SAS URLs for the blobs
If you actually need the bytes in your react app, then just fetch it with a javascript web request - you'll need to set a CORS policy on the blob container though
If you really want to download the file to/via the server, you'll probably have to get into streaming it to the response stream connected to the react app, passed into the SOMETHING below:
BlobClient blob = blobContainerClient.GetBlobClient( BLOB NAME I.E PATH INSIDE CONTAINER);
//download to a file or stream
await blob.DownloadToAsync( SOMETHING );

Azure blob storage returns 404 with some files

I have an Azure blob storage setup with a couple of files in it. I am able to download the files into a Stream when they are small (KB sized), but when the files are a little larger (MB sized) I get a 404 error. I have manually downloaded from the portal one of the images that is returning 404 fine and have resized that image and then uploaded the smaller image back to the container and I can then grammatically download it into a stream.
Here is the code that I'm using to download the blob
private static byte[] PerformDownload(string fileName, CloudBlobContainer container)
{
var blockBlob = container.GetBlockBlobReference(fileName);
using (var memoryStream = new MemoryStream())
{
blockBlob.DownloadToStream(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
var binaryReader = new BinaryReader(memoryStream);
var bytes = binaryReader.ReadBytes((int)memoryStream.Length);
return bytes;
}
}
The container is passed into this method and as I mentioned I can download some files from the container without issue, but if you need that code I can add that as well
The container is retrieve using the standard examples that you find, but here is the code
private static CloudBlobContainer GetContainer(string containerName)
{
var storageAccount = CloudStorageAccount.Parse(ConnectionString);
var container = CreateContainerIfNeeded(storageAccount, containerName);
return container;
}
private static CloudBlobContainer CreateContainerIfNeeded(CloudStorageAccount storageAccount, string containerName)
{
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists();
return container;
}
Also Case sensitivity is not the issue because the container's name is 2017-106 and the file is 4448.jpg.
I am able to download the files into a Stream when they are small (KB sized), but when the files are a little larger (MB sized) I get a 404 error.
Currently max size of a block blob is approx. 4.75 TB, storing MB-sized data in a block blob, which should not cause Azure Blob service return 404 when you access the blob. 404 error indicates that the specified blob does not exist, as Gaurav Mantri said, Blob name is case-sensitive, please make sure the filename (blob name) you provided indeed exists in your container.
Besides, If only that specific blob can not be found, but it is really existing in your container, you can create support request to report it.

Upload file to Azure Blob from HTML webpage (C#)?

I am trying to figure out how to take a file from an html form and save it to my Azure Blob storage. I have found many posts about doing this for JavaScript but I am trying to do it via C#. One source I found said to do
using (YourFileUpload.PostedFile.InputStream)
{
blockBlob.UploadFromStream((FileStream)YourFileUpload.PostedFile.InputStream);
}
but PostedFile does not exist in the HttpPostedFileBase object.
The code I have built out so far is
public static int UploadFile(string FileName, HttpPostedFileBase UploadedFile, int ExistingFileID = 0)
{
var StorageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"].ToString());
var BlobClient = StorageAccount.CreateCloudBlobClient();
var Container = BlobClient.GetContainerReference("ffinfofiles");
var BlobBlock = Container.GetBlockBlobReference(FileName);
var FileExtension = Path.GetExtension(UploadedFile.FileName.ToLower());
using (UploadedFile.InputStream)
{
BlobBlock.UploadFromStream((FileStream)UploadedFile.InputStream);
}
but when I run this I get the error:
Unable to cast object of type 'System.Web.HttpInputStream' to type 'System.IO.FileStream'.
What method do I need to do so I can upload the file to the Azure Blob?
You should not try to cast UploadedFile.InputStream to a FileStream. CloudBlockBlob.UploadFromStream requires a Stream object, so it should be able to work directly with UploadedFile.InputStream.

Azure SAS download blob

I'm trying to download a blob with SAS and kinda clueless right now.
I'm listing all the belonging user blobs in a view. When a user clicks on the blob its supposed to start downloading it.
Here is the view:
#foreach (var file in Model)
{
<a href='#Url.Action("GetSaSForBlob", "Folder", new { blob = file })>
</a>
}
Here is my two functions located in "Folder" controller.
public void GetSaSForBlob(CloudBlockBlob blob)
{
var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(3),
Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,
});
DownloadFileTest(string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas));
//return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas);
}
static void DownloadFileTest(string blobSasUri)
{
CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobSasUri));
using (MemoryStream ms = new MemoryStream())
{
blob.DownloadToStream(ms);
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, data.Length);
}
}
What should i be passing from my view to GetSasForBlob? At the moment CloudBlockBlob blob is null.
Am i missing any code in function DownloadFileTest?
Should i be calling DownloadFileTest directly from GetSasForBlob?
How can i protect these two functions so people cant access them outside the view? They are both static functions now. I'm guessing that is not safe?
1, What the value is of your file in your view. I don't think MVC can create CloudBlockBlob object based on the file you provided. So this might be the reason you got null of your CloudBlockBlob.
2, In your DownloadFileTest you just download the binaries of the blob into the memory stream in your server and that's all. If you need to let user download it to local disk you need to put the binaries into Response.Stream. You can just use something like blob.DownloadToStram(Response.Stream).
3, That's up to you. You can merge them in the same method if you want.
4, If you want user to download blob through your web front (website or web service), as what you are doing now, you need to set your blob container as private and secure your website or web service by using something loke [Authorize] attribute. Basically in your case you really don't need to use SAS at all because all download requests are performed through your web front.
Hope this helps a bit.

Categories