Introduction
This article showsan example of uploading a file in the ASP.NET Web API. Uploading the file from the client is a basic operation. The file can be upload to the web server. By default, the process of file uploading is asynchronous. The developers of ASP.NET use the HTML file input field.
Now I illustrate the process of uploading a file to the web server.
Step 1
Create a MVC4 Web API application "FileUpload".
- Start Visual Studio 2010 and select "New Project" from the Start Page.
- In the Template window, select "Installed template" -> "Visual C#" -> "Web".
- Choose "ASP. NET MVC 4 Web Application" then change its name.
- Click on the "OK" button.
- Select "Web API" and click on the "OK" button.
Step 2
Change the name of "ValuesController" to "DocFileController.cs".
- In the Solution Explorer.
- Select "Controller Folder" -> "ValuesController.cs".
- Rename the "ValuesController" to "DocFileController".
Write this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.IO;
namespace FileUpload.Controllers
{
public class DocFileController : ApiController
{
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
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("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
}
The code above uses the "POST" method. This method looks for the request object. If there is any posted file then it will generate on the server and it returns the full path of the file. If there is no posted file then it returns the 401 status and bad request.
Step 3
Open the "index.cshtml" file then:
And write this code in this file:
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="~/">ASP.NET Web API File Upload</a></p>
</div>
</div>
</header>
<div id="body">
<form name="form1" method="post" action="api/docfile" enctype="multipart/form-data">
<div>
<label>
Brows File</label>
<input name="myFile" type="file" />
</div>
<div>
<input type="submit" value="Upload" />
</div>
</form>
Step 4
Now execute the application; press F5.
Click on the "Browse" button.
Select one image and click on the "Open" button. It now shows the path of the file.
Now click on the "Upload" button.
Now it shows the path where the selected file is saved.