【问题标题】:Try to insert image as a binary into the database尝试将图像作为二进制文件插入数据库
【发布时间】:2021-05-21 06:21:07
【问题描述】:

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

此资源不支持请求实体的媒体类型“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!" });
    }

【问题讨论】:

    标签: c# entity-framework asp.net-web-api2


    【解决方案1】:

    这不是数据库二进制存储的问题,而是使用 web api 上传文件的问题。请参考这里 How to set up a Web API controller for multipart/form-data

    【讨论】:

    • 感谢您的帮助。这无助于解决我的问题。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多