Vlad Levchenko
Vlad Levchenko

Reputation: 301

Posting file from MVC to WEB API

I have a thin ASP.NET MVC client and a WEB API back end. I need to receive excel file on MVC side and the send it to WEB API controller without any changes. How can I achieve it in most simple way?

[HttpPost]
public ActionResult UploadExcelFile(HttpPostedFileBase file)
{
   //call web api here 
} 

Right now I'm thinking of creating an UploadFileRequest that will look like this:

public class UploadFileRequest 
{
    public byte[] byteData { get; set; }
}

and pass file as byte array, however this looks extremely inefficient.

Upvotes: 1

Views: 7901

Answers (2)

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

I have created a sample for uploading files from MVC controller to Web Api controller, and it's working perfectly

MVC controller :

    [ActionName("FileUpload")]
    [HttpPost]
    public ActionResult FileUpload_Post()
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            using (HttpClient client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    byte[] fileBytes = new byte[file.InputStream.Length + 1];                         
                    file.InputStream.Read(fileBytes, 0, fileBytes.Length);
                    var fileContent = new ByteArrayContent(fileBytes);
                    fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
                    content.Add(fileContent);
                    var result = client.PostAsync(requestUri, content).Result;
                    if (result.StatusCode == System.Net.HttpStatusCode.Created)
                    {
                        ViewBag.Message= "Created";
                    }
                    else
                    {
                        ViewBag.Message= "Failed";
                    }
                }
            }
        }
        return View();
    }

Web Api controller :

    [HttpPost]
    public HttpResponseMessage Upload()
    {
        if(!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        if (System.Web.HttpContext.Current.Request.Files.Count > 0)
        {
            var file = System.Web.HttpContext.Current.Request.Files[0];
            ....
            // save the file
            ....
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
        else
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }

For more information on saving file in Web Api, refer Web API: File Upload

Hope that helps someone!

Upvotes: 5

dan
dan

Reputation: 532

From your JS

var data = new FormData();
var file = $("#upload")[0]; // your input[type=file]
data.append("file", file.files[0]);

 $.ajax({
            type: "POST",
            url: url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            async: true,
            success: function(data) {
            }
        });

And from your apicontroller

call HttpContext.Current.Request.Files[0] // here's your file

Upvotes: 1

Related Questions