microsoft.aspnet.http.abstractions中缺少InputStream和ContentLength

时间:2016-04-01 14:25:07

标签: c# asp.net-core asp.net-core-mvc

正如我对Microsoft.AspNet.Http.Abstractions的回顾,IFormFile缺少ASP.NET MVC 6中的InputStream和ContentLength,而不是OpenReadStream,它不能用于转换为ConvertToBytes,例如: / p>

private byte[] ConvertToBytes(IFormFile image)
    {
        byte[] imageBytes = null;
        //Then, Read stream in Binary
        BinaryReader reader = new BinaryReader(image.InputStream);
        imageBytes = reader.ReadBytes((int) image.ContentLength);
        return imageBytes;

    }

你知道InputStream和ContentLength会发生什么吗?在IFormFile中,可以使用OpenReadStream和Length。我不知道如何使用它。有谁知道如何使用它。我想有类似的代码如下例所示:

private byte[] ConvertToBytes(IFormFile image)
    {
        byte[] imageBytes = null;
        //Then, Read stream in Binary
        BinaryReader reader = new BinaryReader(image.OpenReadStream());
        imageBytes = reader.ReadBytes((int) image.Length);
        return imageBytes;

    }

我在下面的代码中尝试了什么,但由于BinaryReader reader = new BinaryReader(image.OpenReadStream())显示System.NullReferenceException未被用户代码处理,因此无法使用HResult = -2147467261 并且Message = Object引用未设置为对象的实例。:

private byte[] ConvertToBytes(IFormFile image)
    {
        byte[] imageBytes = null;
        //Then, Read stream in Binary
        BinaryReader reader = new BinaryReader(image.OpenReadStream());
        imageBytes = reader.ReadBytes((int) image.Length);
        return imageBytes;

    }

你能帮我解决这个问题吗?

我调用ConvertToBytes以将图像文件添加到varbinary数据类型的数据库字段中,请参阅下面的代码:

private readonly ApplicationDbContext db = new ApplicationDbContext();
    public int UploadImageInDataBase(IFormFile file, PublisherInfosViewModel publisherInfosViewModel)
    {
        publisherInfosViewModel.Image = ConvertToBytes(file);
        var publisherInfos = new PublisherInfos
        {
            PubInfoId = publisherInfosViewModel.PubInfoId,
            PubId = publisherInfosViewModel.PubId,
            Title = publisherInfosViewModel.Title,
            Image = publisherInfosViewModel.Image,
            Description = publisherInfosViewModel.Description,
            Contents = publisherInfosViewModel.Contents

        };
        db.PublisherInfos.Add(publisherInfos);
        int i = db.SaveChanges();
        if (i == 1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

0 个答案:

没有答案