locked
asp.net upload and download c# RRS feed

  • Question

  • I have made many stabs at doing this based on my reading of many posts.  What I am trying to do is an upload and download to and from a BLOB.  I have a fileupload control for upload and just a button for download.  Here is what I have so far. What path do I use for upload? and feel free to correct any mistakes I have. I think the upload is working with my new fix. Still

    cant get the download to work.

    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Web.UI;
    
    namespace MarksFileLoadTest
    {
        public partial class _Default : Page
        {
            private CloudBlobClient _blobClient;
            private CloudBlockBlob _blockBlob;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                
            }
                   
            protected void btnUpload_Click(object sender, EventArgs e)
            {
                if (FileUpload1.HasFile)
                {
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("HIDDENFORSECURITYREASONS");
                    _blobClient = storageAccount.CreateCloudBlobClient();
    
                    CloudBlobContainer container = _blobClient.GetContainerReference("marksblobcontainer");
    
                    container.CreateIfNotExists();
                    container.SetPermissions(new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
    
                    _blockBlob = container.GetBlockBlobReference("C:\\log\\");  // Path to download to?????
                    
                    using (FileStream fileStream = new FileStream("C:\\log\\" + FileUpload1.FileName, FileMode.OpenOrCreate))
                    {
                        _blockBlob.UploadFromStream(fileStream);
                    }      
                }
            }
    
            protected MemoryStream btnDownload_Click(object sender, EventArgs e)
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse("HIDDENFORSECURITYREASONS");
                _blobClient = storageAccount.CreateCloudBlobClient();
    
                CloudBlobContainer container = _blobClient.GetContainerReference("marksblobcontainer");
    
                container.CreateIfNotExists();
                container.SetPermissions(new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
    
                _blockBlob = container.GetBlockBlobReference(@"C:\temp2\");
    
                MemoryStream ms = new MemoryStream();
                _blockBlob.DownloadToStreamAsync(ms);
                return ms;        
            }
        }
    }

    *** Please allow me to mark threads as answered and I will, Thank you ***




    • Edited by ski_freak Tuesday, January 14, 2020 8:29 PM
    Tuesday, January 14, 2020 7:00 PM

Answers

  • Here is my working solution finally.!

    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Web.UI;

     protected void btnUpload_Click(object sender, EventArgs e)
            {
                if (FileUpload1.HasFile)
                {
                    string uploadPath = "C:\\log\\";
    
                    //set the storage account creds
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("YOURCREDSHERE");
    
                    //get the client
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                    //get the container from the client
                    CloudBlobContainer container = blobClient.GetContainerReference("marksblobcontainer");
    
                    //create?
                    if (container.CreateIfNotExists())
                    {
                        container.SetPermissions(new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        });
                    }
    
                    string filetouse = Path.GetExtension(FileUpload1.FileName);
    
                    //get the file uploaded
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileUpload1.FileName.ToLower());
    
                    //TODO for each type maybe?
                    blockBlob.Properties.ContentType = filetouse.GetType().ToString(); //Seems you need this to work correctly
    
                    using (FileStream fileStream = new FileStream(uploadPath + FileUpload1.FileName, FileMode.OpenOrCreate))
                    {
                        blockBlob.UploadFromStream(fileStream);
                    }
                }
            }
    		
    		protected void btnDownload_Click(object sender, EventArgs e)
            {
                string downloadPath = "C:\\temp2\\";
    
                //set the storage account creds
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse("YOURCREDSHERE");
    
                //get the client
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                //get the container from the client
                CloudBlobContainer container = blobClient.GetContainerReference("marksblobcontainer");
                            
                //go through each item in the blob and download it
                foreach (IListBlobItem item in container.ListBlobs())
                {                
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        //get name from db eventually and                        replace item.Uri.Segments[2]   TODO
                        CloudBlockBlob blockBlob = container.GetBlockBlobReference(item.Uri.Segments[2]);
    
                        blockBlob.DownloadToStream(memoryStream);
                        memoryStream.Position = 0;
                        StreamReader sr = new StreamReader(memoryStream);
                        string strFile = sr.ReadToEnd();
    
                        FileStream fs = new FileStream(downloadPath + item.Uri.Segments[2], FileMode.OpenOrCreate, FileAccess.Write);
                        memoryStream.WriteTo(fs);
                        fs.Close();                   
                    }               
                }         
            }       

    *** Please allow me to mark threads as answered and I will, Thank you ***


    • Marked as answer by ski_freak Thursday, January 16, 2020 7:58 PM
    • Edited by ski_freak Thursday, January 16, 2020 7:59 PM
    Thursday, January 16, 2020 7:58 PM

All replies

  • So the download does work but ONLY if I specify the file that was uploaded.  How can I find the name from a BLOB vs hard coding it?

    *** Please allow me to mark threads as answered and I will, Thank you ***

    Wednesday, January 15, 2020 2:49 PM
  • I also need to make my blob name the same as the file I upload.  i.e. mylog.txt but I keep getting a 400.  I tried \mylog.txt as well.  HELP!

    *** Please allow me to mark threads as answered and I will, Thank you ***

    Wednesday, January 15, 2020 4:40 PM
  • Have you by any chance checked the following documentation: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet 

    There's a code section specific to downloading and uploading a blob, you can find more info here: 


    // Create a local file in the ./data/ directory for uploading and downloading
    string localPath = "./data/";
    string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
    string localFilePath = Path.Combine(localPath, fileName);
    
    // Write text to the file
    await File.WriteAllTextAsync(localFilePath, "Hello, World!");
    
    // Get a reference to a blob
    BlobClient blobClient = containerClient.GetBlobClient(fileName);
    
    Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
    
    // Open the file and upload its data
    using FileStream uploadFileStream = File.OpenRead(localFilePath);
    await blobClient.UploadAsync(uploadFileStream);
    uploadFileStream.Close();


    Wednesday, January 15, 2020 7:08 PM
  • So I am still having issues.  Let me try to reword.  I want to upload a file from a fileupload control (name is mylog.txt and folder is c:\log).  I could also have .pdf, .xlxs etc.  

    Then

    I want to be able to download the same file w/o hard coding the name.  I will use C:\Temp2 to download the file to.

    I have about 20 versions of trying to accomplish this.  I do not need to use await/async as we are not using threads for this.  I am looking for a working solution as I have spent 2 weeks and nothing yet to show for it.

    Thanks again in advance.


    *** Please allow me to mark threads as answered and I will, Thank you ***

    Wednesday, January 15, 2020 8:17 PM
  • Here is my working solution finally.!

    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Web.UI;

     protected void btnUpload_Click(object sender, EventArgs e)
            {
                if (FileUpload1.HasFile)
                {
                    string uploadPath = "C:\\log\\";
    
                    //set the storage account creds
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("YOURCREDSHERE");
    
                    //get the client
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                    //get the container from the client
                    CloudBlobContainer container = blobClient.GetContainerReference("marksblobcontainer");
    
                    //create?
                    if (container.CreateIfNotExists())
                    {
                        container.SetPermissions(new BlobContainerPermissions
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        });
                    }
    
                    string filetouse = Path.GetExtension(FileUpload1.FileName);
    
                    //get the file uploaded
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileUpload1.FileName.ToLower());
    
                    //TODO for each type maybe?
                    blockBlob.Properties.ContentType = filetouse.GetType().ToString(); //Seems you need this to work correctly
    
                    using (FileStream fileStream = new FileStream(uploadPath + FileUpload1.FileName, FileMode.OpenOrCreate))
                    {
                        blockBlob.UploadFromStream(fileStream);
                    }
                }
            }
    		
    		protected void btnDownload_Click(object sender, EventArgs e)
            {
                string downloadPath = "C:\\temp2\\";
    
                //set the storage account creds
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse("YOURCREDSHERE");
    
                //get the client
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                //get the container from the client
                CloudBlobContainer container = blobClient.GetContainerReference("marksblobcontainer");
                            
                //go through each item in the blob and download it
                foreach (IListBlobItem item in container.ListBlobs())
                {                
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        //get name from db eventually and                        replace item.Uri.Segments[2]   TODO
                        CloudBlockBlob blockBlob = container.GetBlockBlobReference(item.Uri.Segments[2]);
    
                        blockBlob.DownloadToStream(memoryStream);
                        memoryStream.Position = 0;
                        StreamReader sr = new StreamReader(memoryStream);
                        string strFile = sr.ReadToEnd();
    
                        FileStream fs = new FileStream(downloadPath + item.Uri.Segments[2], FileMode.OpenOrCreate, FileAccess.Write);
                        memoryStream.WriteTo(fs);
                        fs.Close();                   
                    }               
                }         
            }       

    *** Please allow me to mark threads as answered and I will, Thank you ***


    • Marked as answer by ski_freak Thursday, January 16, 2020 7:58 PM
    • Edited by ski_freak Thursday, January 16, 2020 7:59 PM
    Thursday, January 16, 2020 7:58 PM
  • @ski_freak Glad to hear that issue got fixed. Appreciate for sharing the steps which helped you, this would certainly benefit other community members

    Monday, January 20, 2020 6:11 AM