繁体   English   中英

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

[英]Try to insert image as a binary into the database

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

此资源不支持请求实体的媒体类型“multipart/form-data”

这是我尝试过的代码:

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

这不是数据库二进制存储的问题,而是使用 web api 上传文件的问题。 请参阅如何为多部分/表单数据设置 Web API controller

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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