4

I've set up an Azure Blob Storage to upload/download file.

ProcessAsync(Folderpath, rows.Item("FileName"), rows.Item("Extension")).GetAwaiter().GetResult()
System.IO.File.Move(Folderpath + "\" + rows.Item("FileName"), AchivePath + "\" + rows.Item("FileName"))
WriteToLog("Extracted File : " + rows.Item("FileName") + " ", "")
DownloadBlobSnapshot(rows.Item("FileName"), rows.Item("Extension")).GetAwaiter().GetResult()

Currently, I am able to store my file locally in my desktop. How do I save and display the file on .net MVC platform with Using and MemoryStream/FileStream?

Or alternatively, is there any better way in doing so?

Edit 1: (Based on Ivan's Answer)

Private Shared Async Function DownloadBlobSnapshot(FileName As String, Extension As String) As Task

Dim storageAccount As CloudStorageAccount
Dim storageConnectionString As String = ConfigurationManager.AppSettings("StorageConnectionString")
Dim accountName As String = myaccountname
Dim accountKey As String = myaccountkey
Dim cred = New StorageCredentials(accountName, accountKey)
Dim account = New CloudStorageAccount(cred, True)
Dim client = account.CreateCloudBlobClient()
Dim container = client.GetContainerReference(FileName.Replace(Extension, ""))
Dim listOfBlobs As IEnumerable = container.ListBlobs(Nothing, True, BlobListingDetails.Snapshots)

If CloudStorageAccount.TryParse(storageConnectionString, storageAccount) Then
   For Each item In listOfBlobs
       Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference((CType(item, CloudBlockBlob)).Name)
       blockBlob.DownloadToStream(Response.OutputStream)
   Next
       //ToDO
        End If
End Function

But I'd realised Response is not available in Shared Function.

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
PartTimeNerd
  • 305
  • 1
  • 2
  • 20

2 Answers2

5

You can use DownloadToStream.

Sample code as below(asp.net mvc project):

        public ActionResult DownloadFile()
        {
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("your_account", "your_key"),true);
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = client.GetContainerReference("t11");
            CloudBlockBlob blob = blobContainer.GetBlockBlobReference("ss22.pdf");

            blob.DownloadToStream(Response.OutputStream);

            return new EmptyResult();
        }

Update 1: upload the screenshot of vb.net mvc project: enter image description here

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60
  • It's a vb.net project? I'm not familiar with it:( . But have you created an vb.net mvc project and write the code in xxxcontroller.vb? I create an vb.net mvc project, and the Response is ok there. Later, I will add the screenshot to my answer. – Ivan Glasenberg Nov 23 '18 at 03:17
  • Probably its due to my method declaration, seems like we can't use `Response` in a `shared` method – PartTimeNerd Nov 23 '18 at 03:48
  • Not sure because I'm not familiar with vb,if it's c#, I can do more investigation on it:) . – Ivan Glasenberg Nov 23 '18 at 04:02
5

For those who've encountered the same issue as me.

Function DownloadBlobSnapshot(FileName As String, Extension As String) As ActionResult

    Dim storageAccount As CloudStorageAccount
    Dim storageConnectionString As String = ConfigurationManager.AppSettings("StorageConnectionString")
    Dim accountName As String = myaccountname
    Dim accountKey As String = myaccountkey
    Dim cred = New StorageCredentials(accountName, accountKey)
    Dim account = New CloudStorageAccount(cred, True)
    Dim client = account.CreateCloudBlobClient()
    Dim container = client.GetContainerReference("myfilename")
    Dim fileStream As New MemoryStream
    fileStream.Position = 0
    Dim listOfBlobs As IEnumerable = container.ListBlobs(Nothing, True, BlobListingDetails.Snapshots)

    Try
        If CloudStorageAccount.TryParse(storageConnectionString, storageAccount) Then
            For Each item In listOfBlobs
                Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference((CType(item, CloudBlockBlob)).Name)
                blockBlob.DownloadToStream(fileStream)
                Response.Clear()
                Response.ContentType = "application/force-download"
                Response.AddHeader("content-disposition", "inline; filename=name_you_file.pdf")
                Response.BinaryWrite(fileStream.ToArray)
                Response.End()

                Return New FileStreamResult(fileStream, "application/pdf")

            Next

        End If
    Catch ex As Exception

    End Try

End Function

Updated: 29/11/2018

Function DownloadBlobSnapshot(FilePath As String, LabCompany As String, FileName As String) As ActionResult

    Dim storageAccount As CloudStorageAccount
    Dim cloudBlobContainer As CloudBlobContainer = Nothing
    Dim sourceFile As String = Nothing
    Dim destinationFile As String = Nothing
    Dim storageConnectionString As String = (CASAuthentication.Decrypt(Configs.BlobConnectionString))
    Dim url As String = ""
    Dim sasToken As String = ""

    If CloudStorageAccount.TryParse(storageConnectionString, storageAccount) Then
        Try

            Dim cloudBlobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()

            cloudBlobContainer = cloudBlobClient.GetContainerReference(LabCompany.ToLower)
            If cloudBlobContainer.Exists() Then
                Dim cloudBlockBlob As CloudBlockBlob = cloudBlobContainer.GetBlockBlobReference((FileName))
                If cloudBlockBlob.Exists Then
                    url = cloudBlockBlob.Uri.AbsoluteUri()

                    Dim sharedPolicy As SharedAccessBlobPolicy = New SharedAccessBlobPolicy() With {
            .SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(Integer.Parse(ConfigurationManager.AppSettings("PDFTimeOut"))),
            .Permissions = SharedAccessBlobPermissions.Read Or SharedAccessBlobPermissions.Write
        }

                    sasToken = cloudBlockBlob.GetSharedAccessSignature(sharedPolicy)

                End If
            End If

                Return Json(New With {.success = True, .url = url + sasToken}, JsonRequestBehavior.AllowGet)

        Catch ex As Exception
            Return Json(New With {.success = False, .message = ex.ToString}, JsonRequestBehavior.AllowGet)
        Finally

        End Try

    Else
        Return Json(New With {.success = False, .message = "Failed to receive report data. Please try again later."}, JsonRequestBehavior.AllowGet)
    End If

End Function

Displaying using ajax

var tabledata =  {mydata: data}
    $.ajax({
        cache: false,
        type: "POST",
        url: "/Home/DownloadBlobSnapshot",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(tabledata),
        success: function (result) {
            var e = result.url
            //e.substr(0, e.lastIndexOf("/"))
            e = "http://docs.google.com/viewer?url=" + encodeURIComponent(e) + "&embedded=true";
            popitup(e);
        },

        error: function () {

        }
    });
PartTimeNerd
  • 305
  • 1
  • 2
  • 20