尝试将图像作为二进制文件插入数据库

Try to insert image as a binary into the database

当我尝试将图像作为二进制文件添加到我的数据库中时,使用 ASP.NET Web API 2 使用 Entity Framework。我收到此错误:

The request entity's media type 'multipart/form-data' is not supported for this resource

这是我试过的代码:

[HttpPost]
public IHttpActionResult ImageUpload(HttpPostedFileBase postedFile)
{
        byte[] bytes;

        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }

        SchoolContext context = new SchoolContext();

        context.Images.Add(new Image
        {
            Name = Path.GetFileName(postedFile.FileName),
            ContentType = postedFile.ContentType,
            ImageBinary = bytes
        });

        context.SaveChanges();

        return Ok(new { messages = "Image uploaded!" });
    }

这不是数据库二进制存储的问题,而是使用网络上传文件的问题api。请参考这个

我找到了另一种将图片上传到数据库的方法。以下是对我有用的代码。

 [HttpPost]
    [Route("api/FileAPI/SaveFile")]
    public HttpResponseMessage SaveFile()
    {
        
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

        
        if (HttpContext.Current.Request.Files.Count == 0)
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        
        HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

        
        byte[] bytes;
        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }

        SchoolContext entities = new SchoolContext();
        ImageBinary file = new ImageBinary
        {
            Name = Path.GetFileName(postedFile.FileName),
            ContentType = postedFile.ContentType,
            Data = bytes
        };
        entities.ImageBinaries.Add(file);
        entities.SaveChanges();

        return Request.CreateResponse(HttpStatusCode.OK, new { id = file.id, Name = file.Name });
    }