Wednesday, May 4, 2016
File upload and download using JQuery and submit button ASP.net
0 comments Posted by Duc Nguyen at 8:33 PMThe 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>
Subscribe to:
Posts (Atom)