ASP.NET Web API Azure Blob存储非结构化 [英] ASP.NET Web API Azure Blob Storage Unstructured

查看:53
本文介绍了ASP.NET Web API Azure Blob存储非结构化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个ASP.NET Web API项目,该项目需要使用Azure blob存储上载word文档.我有一种创建用户配置文件的方法,但是不幸的是,我遇到了与天蓝色blob存储和上载文档有关的问题.调试时,IFormFile文档为null,并且与azure的连接也为null.我不知道断开连接在哪里.如果有人知道解决方案,我将不胜感激.以下是我编写的代码.

I have an ASP.NET Web API project that I'm building that requires uploading word documents using Azure blob storage. I have a method that creates a user profile but unfortunately, I'm encountering issues related to azure blob storage and uploading a document. When debugging, the IFormFile document is null, and the connection to azure is null as well. I can't figure out where the disconnect is. I'd appreciate if someone knows the solution. Below is the code that I've written.

型号

Person Model

public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get;set;}
public string URL {get;set;}
public string DocName {get;set;}
public string IFormFile[] DocUpload {get;set;}

存储库

public class DocRepo : IDocRepo
{
    private CloudStorageAccount storageAccount = null;
    private CloudBlobContainer cloudBlobContainer = null;

    public IConfiguration _config { get; }

    private readonly ILogger _logger;

    public DocRepo(ILogger logger)
    {
        _logger = logger;
    }


    public void Configure()
    {
        var AzConnectionString = _config["AzConnectionString"];

        if (CloudStorageAccount.TryParse(AzConnectionString, out storageAccount))
        {
            try
            {
                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

                cloudBlobContainer = cloudBlobClient.GetContainerReference("folder");
                cloudBlobContainer.CreateAsync().GetAwaiter().GetResult();

                BlobContainerPermissions permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                cloudBlobContainer.SetPermissionsAsync(permissions).GetAwaiter().GetResult();
            }
            catch (StorageException ex)
            {
                _logger.LogError("Error returned from the service: {0}", ex);
            }
            _logger.LogInformation("Success");
        }
        else
        {
            _logger.LogInformation("No Connection");
        }
    }



    public async Task Upload(IFormFile[] docuFile)
    {
        Person person = new Person();
        person.DocUpload = docuFile;

        List<string> url = new List<string>();
        List<string> docName = new List<string>();

        try
        {
            if (docuFile != null)
            {
                foreach (var file in docuFile)
                {

                    if (file.ContentType == "application/msword")
                    {
                        if (file.Length < 5 * 1400 * 1400)
                        {
                            var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                            var filename = parsedContentDisposition.FileName.Trim('"');
                            docName.Add(filename);

                            filename = Guid.NewGuid().ToString() + "-" + filename;

                            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename);
                            cloudBlockBlob.Properties.ContentType = file.ContentType;
                            await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());

                            url.Add(cloudBlockBlob.Uri.AbsoluteUri);
                        }
                        else
                        {
                            _logger.LogInformation("5 mb max size allowed");
                        }
                    }
                    else
                    {
                        _logger.LogInformation("Only .doc format accepted");
                    }
                }
                person.URL = (urls.Count > 0) ? string.Join(" || ", urls) : null;
                person.DocName = string.Join(" || ", name);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error uploading");
        }
    }

接口

 public interface IDocRepo
{
    void Configure();
    Task Upload(IFormFile[] doc);
}

PersonController

PersonController

[HttpPost]
            public async Task<IActionResult> Create([FromBody] Person person)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        _docRepo.CreateConfigure();
                        await _docRepo.Upload(person.DocUpload);
                        _context.Person.Add(person);
                        await _context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                return CreatedAtAction("PersonCreated", new { id = person.Id }, person);
            }

推荐答案

我对您的代码进行了一些更改,并删除了一些编译错误. 看一下这段代码.我能够上传文件(经过邮递员测试).我删除了一些配置代码(直接在代码中使用了连接字符串",但这不会影响主代码.

I made few changes to your code and removed some compilation errors. Take a look a this code. I am able to upload files ( tested with postman ). I removed some of the config code( used connection string directly in code" but that shouldn't affect main code.

人物模型

namespace WebApplication8.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string URL { get; set; }
        public string DocName { get; set; }
        public IList<IFormFile> docs {get;set;}
    }
}

DeleteRequest模型

DeleteRequest Model

namespace WebApplication8.Models
{
    public class DeleteRequest
    {
        public string container;
        public IList<string> docs;
    }
}

PersonController

PersonController

[Route("api/Person")]
public class PersonController : Controller
{
    private readonly ILogger<PersonController> _logger;
    private readonly IDocRepo _docRepo;

    public PersonController(ILogger<PersonController> logger, IDocRepo docRepo)
    {
        _logger = logger;
        _docRepo = docRepo;
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromForm] Person person)
    {
        if (ModelState.IsValid)
        {
            try
            {
                _docRepo.Configure();
                await _docRepo.Upload(person.docs);
                //_context.Person.Add(person);
                //await _context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Ok();
        }
        else
        {
            return BadRequest();
        }

    }
}

    [HttpDelete]
    public async Task<IActionResult> Delete([FromBody] DeleteRequest deleteRequest)
    {

        if (ModelState.IsValid)
        {
            try
            {
                _docRepo.Configure();
                await _docRepo.Delete(deleteRequest.docs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return Ok();
        }
        else
        {
            return BadRequest();
        }
    }

IDocRepo和DocRepo

IDocRepo and DocRepo

public interface IDocRepo
{
    void Configure();
    Task Upload(IList<IFormFile> pdfFiles);
    Task Delete(IList<string> docs);
}

public class DocRepo : IDocRepo
{
    private CloudStorageAccount storageAccount = null;
    private CloudBlobContainer cloudBlobContainer = null;


    private readonly ILogger<DocRepo> _logger;

    public DocRepo(ILogger<DocRepo> logger)
    {
        _logger = logger;
    }


    public void Configure()
    {
        var AzConnectionString = "<<Add your connection string >>";

        if (CloudStorageAccount.TryParse(AzConnectionString, out storageAccount))
        {
            try
            {
                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                cloudBlobContainer = cloudBlobClient.GetContainerReference("folder");
                cloudBlobContainer.CreateAsync().GetAwaiter().GetResult();

                BlobContainerPermissions permissions = new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                };
                cloudBlobContainer.SetPermissionsAsync(permissions).GetAwaiter().GetResult();
            }
            catch (StorageException ex)
            {
                _logger.LogError("Error returned from the service: {0}", ex);
            }
            _logger.LogInformation("Success");
        }
        else
        {
            _logger.LogInformation("No Connection");
        }
    }



    public async Task Upload(IList<IFormFile> docs)
    {
        //Person person = new Person();
        //person.docs = new List<IFormFile>(docs);

        List<string> url = new List<string>();
        List<string> docName = new List<string>();

        try
        {
            if (docs != null)
            {
                foreach (var file in docs)
                {

                    if (file.ContentType == "application/msword")
                    {
                        if (file.Length < 5 * 1400 * 1400)
                        {
                            var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

                            var filename = parsedContentDisposition.FileName.Trim('"');
                            docName.Add(filename);

                            filename = Guid.NewGuid().ToString() + "-" + filename;

                            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename);
                            cloudBlockBlob.Properties.ContentType = file.ContentType;
                            await cloudBlockBlob.UploadFromStreamAsync(file.OpenReadStream());

                            url.Add(cloudBlockBlob.Uri.AbsoluteUri);
                        }
                        else
                        {
                            _logger.LogInformation("5 mb max size allowed");
                        }
                    }
                    else
                    {
                        _logger.LogInformation("Only .doc format accepted");
                    }
                }
                //person.URL = (url.Count > 0) ? string.Join(" || ", url) : null;
                //person.DocName = string.Join(" || ", file.);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error uploading");
        }
    }
}

    public async Task Delete(IList<string> docs)
    {
        foreach (var doc in docs)
        {
            try
            {
                CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference(doc);
                await blockBlob.DeleteIfExistsAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting blob " + doc);
            }
        }
    }

更改了Startup.cs中的代码段

changed snippet from Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped<IDocRepo, DocRepo>();
}

这篇关于ASP.NET Web API Azure Blob存储非结构化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆