4

Client side code:

<form action="api/MyAPI" method="post" enctype="multipart/form-data">     
<label for="somefile">File</label>     <input name="somefile" type="file" />     
<input type="submit" value="Submit" /> 
</form>

And how to process upload file with mvc web-api,have some sample code?

j0k
  • 22,600
  • 28
  • 79
  • 90
Ray
  • 127
  • 1
  • 3
  • 10

2 Answers2

1

HTML Code:

<form action="api/MyAPI" method="post" enctype="multipart/form-data">     
    <label for="somefile">File</label>     
     <input name="somefile" type="file" />     
    <input type="submit" value="Submit" /> 
    </form>

Controller

         // POST api/MyAPI
        public HttpResponseMessage Post()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.AllKeys[0] == "image")
            {
                if (httpRequest.Files.Count > 0)
                {
                    var docfiles = new List<string>();
                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];
                        var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
                        postedFile.SaveAs(filePath);

                        docfiles.Add(filePath);
                    }
                    result = Request.CreateResponse(HttpStatusCode.Created, docfiles);


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

try below link

this link use for me hopefully it will work you

http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2

vakeel
  • 287
  • 2
  • 7
0

You can use ApiMultipartFormFormmatter to upload file to web api 2. By using this library, you can define a view model to get parameters submitted from client-side. Such as:

public class UploadFileViewModel 
{
    public HttpFile Somefile{get;set;}
}

And use it in your Api controller like this:

public IHttpActionResult Upload(UploadFileViewModel info)
{
    if (info == null)
    {
        info = new UploadFileViewModel();
        Validate(info);
    }

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    return Ok();
}

Nested objects can be parsed by this library.

Redplane
  • 2,971
  • 4
  • 30
  • 59