2012-12-07

WebApi: File upload and download using JQuery and submit button

,

I am going to create a WebApi service called FileService that can be used to upload and download files. The service will only contain 2 methods. A Post to upload and a Get method that accepts an id parameter to identify the file that needs to be downloaded. Let’s start with the Post method.

The Post method

This method will look in the Request object to see if there are any posted files. If so, it will loop over the files and create them on the server side. The server will return a 201 HttpStatus and a list of strings that will contain the full path of the file(s) at server side. When there are no files posted, the service will return a 401 status a.k.a. BadRequest.

public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;

// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();

// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs( filePath);

files.Add(filePath);
}

// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}

return result;
}

The Get Method


As mentioned before, the Get Method will accept a string file that will identify (= filename) the file that needs to be downloaded.

public HttpResponseMessage Get(string id)
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/" + id);

// check if parameter is valid
if (String.IsNullOrEmpty(id))
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
// check if file exists on the server
else if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{// serve the file to the client
result = Request.CreateResponse( HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = id;
}

return result;
}

Uploading a File


Using a submit  button

 <form name="form1" method="post" action="api/file" enctype="multipart/form-data">
<
div>
<
label>
Using submit</label>
<
input name="myFile" type="file" />
</
div>
<
div>
<
input type="submit" value="Submit" />
</
div>
</
form>


Using JQuery

<form enctype="multipart/form-data">
<
label>
Using JQuery</label>
<
input name="file" type="file" />
<
input type="button" id="Upload" value="Upload" />
</
form>
        <script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: 'api/file',
type: 'POST',
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
});
});
</script>

Downloading a File


image


Summary


The solution can be downloaded here.

10 comments:

  1. This is working excellent with Chrome & Firefox but not working with IE. Please Help me. Advance Thanks

    ReplyDelete
  2. Hi, thanks a lot for this article, I want to ask you how can I use this code to upload file into dropbox, I've made registration for dropbox App. The problem is that my task is to upload the file with web service( ASP.NET WebAPI).
    My idea is to upload the file in dropbox, then return the link and record it in database in AppHarbor ?

    ReplyDelete
  3. Very nice documentation on uploading files, but none regarding downloading files. Could you pls add that to the content?

    ReplyDelete
  4. At last full working demo. Everything else that I find today have a plenty of errors and not work. Thank you for you help.

    ReplyDelete
  5. What is the maximum length of the file that can be uploaded?

    Thanks

    ReplyDelete
  6. This Get method will only allow one file download at a time. Check out for Async: https://stackoverflow.com/questions/21533022/web-api-2-download-file-using-async-taskihttpactionresult

    ReplyDelete
  7. Does it work for IE8?

    ReplyDelete