- Back to Home »
- Ajax , C# , Generic Handler , jQuery »
Posted by : Jebastin
Tuesday, 21 January 2014
The following AJAX File Upload jQuery Tutorial covers how to upload files asynchronously using jQuery Framework.
Generic Handler: AjaxFileUploader.ashx
- public class AjaxFileUploader : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- if (context.Request.Files.Count > 0)
- {
- string path = context.Server.MapPath("~/Files");
- if (!Directory.Exists(path))
- Directory.CreateDirectory(path);
- var file = context.Request.Files[0];
- string fileName;
- if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
- {
- string[] files = file.FileName.Split(new char[] { '\\' });
- fileName = files[files.Length - 1];
- }
- else
- {
- fileName = file.FileName;
- }
- string strFileName = fileName;
- fileName = Path.Combine(path, fileName);
- file.SaveAs(fileName);
- string msg = "{";
- msg += string.Format("error:'{0}',\n", string.Empty);
- msg += string.Format("msg:'{0}',\n", strFileName);
- msg += string.Format("path:'{0}'", path.Replace("\\", "?"));
- msg += "}";
- context.Response.Write(msg);
- }
- }
- public bool IsReusable
- {
- get
- {
- return true;
- }
- }
- }
HTML:
- <div class="resumeUpload">
- <input type="file" id="fileToUpload" name="fileToUpload" onchange="ajaxFileUpload();" />
- <div class="fileBtn">
- <span>File</span>
- <input id="fileUploadBox" disabled="disabled" value="@GetDictionary("No files selected")" />
- </div>
- </div>
jQuery:
- <script type="text/javascript">
- function ajaxFileUpload() {
- $("#fileToUpload").ajaxStart(function () {
- $('#fileUploadBox').val('Uploading...');
- $('#fileUploadBox').addClass('loadinggif');
- }).ajaxComplete(function () {
- $('#fileUploadBox').removeClass('loadinggif');
- });
- $.ajaxFileUpload({
- url: '/GenericHandlers/AjaxFileUploader.ashx',
- secureuri: false,
- fileElementId: 'fileToUpload',
- dataType: 'json',
- data: { name: 'logan', id: 'id' },
- success: function (data, status) {
- if (typeof (data.error) != 'undefined') {
- if (data.error != '') {
- //alert(data.error);
- } else {
- $('#fileUploadBox').val(data.msg);
- $("#hdnFilePath").val(data.path + "?" + data.msg);
- }
- }
- },
- error: function (data, status, e) {
- //alert(e);
- $('#fileUploadBox').val('File size is too large.');
- }
- });
- $.extend({
- handleError: function (s, xhr, status, e) {
- if (s.error)
- s.error(xhr, status, e);
- else if (xhr.responseText)
- console.log(xhr.responseText);
- }
- });
- return false;
- }
- </script>