0

When I tried to add the image as binary into my database, using ASP.NET Web API 2 using Entity Framework. I'm getting this error:

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

This is the code which I tried:

[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!" });
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Brody
  • 35
  • 7

2 Answers2

0

it's not the problem with database binary storing, it's the issue with uploading file using web api. Please refer this How to set up a Web API controller for multipart/form-data

Mon
  • 11
  • 2
0

I found another way to upload images into the database. below is the code which worked for me.

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