简体   繁体   中英

How to Upload Files using Azure Storage and Entity Framework

I am using .NET Core MVC in my project. So I have a Document.cs which looks like

public class Document{
     public int DocumentId { get; set; }
     public string DocumentName { get; set; }

     public int DocumentTypeId { get; set; }
     public DocumentType DocumentType { get; set; } 

     public string DocumentFilePath { get; set; } //which contains the File Name for my File Upload function.
}

and my File Upload method is looks like:

[HttpPost]
public async Task<IActionResult> CreateDocument (DocumentModel model)
{
    string uniqueFileName = null;
    if(model.DocumentFilePath != null)
    {
        string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "StoredFiles");
        uniqueFileName = model.DocumentFilePath.FileName;
        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
        await model.DocumentPath.CopyToAsync(new FileStream(filePath, FileMode.Create));
    }
    var entity = new Document()
    {
        DocumentName = model.DocumentName,
        DocumentTypeId = model.DocumentTypeId,
        DocumentFilePath = uniqueFileName,        
    };

     _documentService.Create(entity); // Simple '_context.Set<Document>().Add(entity);'

     return RedirectToAction("CreateDocument");
}

As you see I have also a DocumentModel.cs comes from my View which looks like:

public class DocumentModel
{
    public int DocumentId { get; set; }

    public string DocumentName { get; set; }

    public IFormFile DocumentFilePath { get; set; }

    public int DocumentTypeId { get; set; }

    public List<DocumentType> DocumentTypes { get; set;} //For my SelectList in my View.
}

Okay, So what this actually does is, as you can simply understand that, upload a file to my "StoredFiles" under my "wwwroot" Folder, and takes the "File Name" and store it in my database.

So I want to start to use Azure Blob Storage. Because I dont want to store files in my project folder. I watched some videos about Azure Storage and how it works but I cant understand how to convert my FileUpload method to an AzureStorage method.

In my opinion I should try to do something like this

[HttpPost]
public async Task<IActionResult> CreateDocument (DocumentModel model)
{
    string uniqueFileName = null;
    if(model.DocumentFilePath != null)
    {
        //I think in this part I have to upload to Azure, then I have to get a 
        //return value for my DocumentFilePath for my "entity" object below.
    }
    var entity = new Document()
    {
        DocumentName = model.DocumentName,
        DocumentTypeId = model.DocumentTypeId,
        DocumentFilePath = uniqueFileName,        
    };

     _documentService.Create(entity); // Simple '_context.Set<Document>().Add(entity);'

     return RedirectToAction("CreateDocument");
}

or I can use seperate methods first one will uploads to azure then second one saves to my Database.

I'd be so happy if you'll help me. Thank you.

If using blob storage, firstly install the NuGet package: Microsoft.Azure.Storage.Blob

Then try below codes:

string storageConnection = CloudConfigurationManager.GetSetting("BlobStorageConnectionString");

CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnection);

CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("appcontainer");

//create a container if it is not already exists

if (await cloudBlobContainer.CreateIfNotExistsAsync())
{

    await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

}


//get Blob reference

CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(model.DocumentFilePath.Name);
cloudBlockBlob.Properties.ContentType = model.DocumentFilePath.ContentType;

using (var stream = model.DocumentFilePath.OpenReadStream())
{
    await cloudBlockBlob.UploadFromStreamAsync(stream);
}

The url of the file in storage will be https://xxxxx.blob.core.windows.net/{ContainerName}/{FileName}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM