0

I have a API method that needs to accept files. I am using Postman chrome plugin to call the api and attach a file.

I added API functionality to my MVC project after creating just an initial MVC web site. don't know if I missed some config but my other API calls work just this one not getting any files.

Here's the code

[Route("~/api/mediaitems/{token}/{eventId}")]
    public async Task<HttpResponseMessage> MediaItems(string token, int eventId, HttpPostedFileBase upload)
    {
        if (upload.ContentLength > 0)
        {
            string _targetFolder = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FilePath"]);
            string _targetPath = Path.Combine(_targetFolder, Guid.NewGuid() + Path.GetFileName(upload.FileName));
            upload.SaveAs(_targetPath);

            var mediaItem = new MediaItem
            {
                MediaFilePath = _targetPath,
                FileType = upload.FileName,
                EventId = eventId,
                CreatedDate = DateTime.Now.Date
            };

            //Save mediaItem
            _repo.SaveMediaItem(mediaItem);

            return Request.CreateResponse(HttpStatusCode.Created);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }           
    }

http://localhost:24727/api/mediaitems/12341254234/1

that's the URL and then I attach the .jpg to the postman body. When I run the api request it never has the file therefore it can never save.

CompiledIO
  • 160
  • 16
  • Can you try with a small file (a text file with a bunch of characters) and use chrome developer tools or fiddler to see and copy here the request body. – Oguz Ozgul Nov 05 '15 at 20:06
  • Did you debug the code? Is `MediaItems` invoked? which branch of `upload.ContentLength > 0` is executed? – Yacoub Massad Nov 05 '15 at 20:12
  • I get a null reference exception on upload and when I add if (upload != null && upload.ContentLength > 0) to if (upload.ContentLength > 0) it just skips and goes to return a bad request which means there is no HttpPostedFileBase – CompiledIO Nov 05 '15 at 20:17
  • Can you describe the steps that you use in Postman to attach the file? – Yacoub Massad Nov 05 '15 at 20:41
  • I insert the URL, select POST and then go to body where I added a file. tried .txt and .png – CompiledIO Nov 05 '15 at 20:48
  • After you click body, do you select "binary"? or "form-data"? – Yacoub Massad Nov 05 '15 at 20:49
  • there is a option to choose between a text and file, I chose file then a openfile dialog popsup – CompiledIO Nov 05 '15 at 20:58
  • I was using form-data switched over to binary and get the following error.....message": "The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.", "exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'application/octet-stream'.", – CompiledIO Nov 06 '15 at 04:43

3 Answers3

0

You can start with something like this:

[Route("~/api/mediaitems/{token}/{eventId}")]
public async Task<HttpResponseMessage> MediaItems(string token, int eventId)
{
    byte[] data = await this.Request.Content.ReadAsByteArrayAsync();

    //data will contain the file content, you can save it here

    return Request.CreateResponse(HttpStatusCode.Created);
}

Notice how I removed the HttpPostedFileBase upload parameter.

You can do some validation based on this.Request.Content if you want. For example, you might want to check the content length.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
  • I do receive the data if I do it this way around but how will I go about saving it to a folder with a filename? – CompiledIO Nov 08 '15 at 06:38
0

Is that an ApiController ? There is not HttpPostedFile in Web API.

You have to use another approach: How to post file to ASP.NET Web Api 2

Community
  • 1
  • 1
vtortola
  • 34,709
  • 29
  • 161
  • 263
0

Maybe help this...Add following to web.config. You must setup max accepted size of file in bytes: 15728640 = 15MB

<configuration>    
    <location path="Custommer/edit">
    <system.web>
      <httpRuntime maxRequestLength="15728640"/>
    </system.web>
  </location>
</configuration>
Miroslav Siska
  • 401
  • 4
  • 15