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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks kleopatra,shabeer90 for your valuable comment
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.