Как загрузить файлы с помощью хранилища Azure и Entity Framework - PullRequest
0 голосов
/ 07 октября 2019

Я использую .NET Core MVC в моем проекте. Итак, у меня есть Document.cs, который выглядит как

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.
}

, и мой метод загрузки файлов выглядит следующим образом:

[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");
}

Как вы видите, у меня также DocumentModel.cs исходит от моегоВид, который выглядит следующим образом:

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.
}

Хорошо, так что на самом деле это так, как вы можете просто понять, загрузите файл в мои "StoredFiles" под моей папкой "wwwroot" и возьмите "Файл"Имя »и сохраните его в моей базе данных.

Поэтому я хочу начать использовать хранилище BLOB-объектов Azure. Потому что я не хочу хранить файлы в папке моего проекта. Я посмотрел несколько видео о хранилище Azure и о том, как оно работает, но не могу понять, как преобразовать мой метод FileUpload в метод AzureStorage.

По моему мнению, я должен попытаться сделать что-то подобное

[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");
}

или я могу использовать отдельные методы: сначала один будет загружен в Azure, а второй сохранен в моей базе данных.

Я был бы очень рад, если вы мне поможете. Спасибо.

1 Ответ

0 голосов
/ 08 октября 2019

При использовании хранилища BLOB-объектов сначала установите пакет NuGet: Microsoft.Azure.Storage.Blob

Затем попробуйте следующие коды:

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);
}

URL-адрес файла в хранилище будет https://xxxxx.blob.core.windows.net/{ContainerName}/{FileName}

...