How to upload file using jQuery/Ajax?

The following AJAX File Upload jQuery Tutorial covers how to upload files asynchronously using jQuery Framework.

Generic Handler: AjaxFileUploader.ashx

  1. public class AjaxFileUploader : IHttpHandler
  2. {
  3. public void ProcessRequest(HttpContext context)
  4. {
  5.     if (context.Request.Files.Count > 0)
  6.     {
  7.         string path = context.Server.MapPath("~/Files");
  8.         if (!Directory.Exists(path))
  9.             Directory.CreateDirectory(path);
  10.         var file = context.Request.Files[0];
  11.         string fileName;
  12.         if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
  13.         {
  14.             string[] files = file.FileName.Split(new char[] { '\\' });
  15.             fileName = files[files.Length - 1];
  16.         }
  17.         else
  18.         {
  19.             fileName = file.FileName;
  20.         }
  21.         string strFileName = fileName;
  22.         fileName = Path.Combine(path, fileName);
  23.         file.SaveAs(fileName);
  24.         string msg = "{";
  25.         msg += string.Format("error:'{0}',\n", string.Empty);
  26.         msg += string.Format("msg:'{0}',\n", strFileName);
  27.         msg += string.Format("path:'{0}'", path.Replace("\\", "?"));
  28.         msg += "}";
  29.         context.Response.Write(msg);
  30.     }
  31. }
  32. public bool IsReusable
  33. {
  34.     get
  35.     {
  36.         return true;
  37.     }
  38. }
  39. }

HTML:

  1. <div class="resumeUpload">
  2.     <input type="file" id="fileToUpload" name="fileToUpload" onchange="ajaxFileUpload();" />
  3.     <div class="fileBtn">
  4.         <span>File</span>
  5.         <input id="fileUploadBox" disabled="disabled" value="@GetDictionary("No files selected")" />
  6.     </div>
  7. </div>

jQuery:

  1. <script type="text/javascript">
  2. function ajaxFileUpload() {
  3.     $("#fileToUpload").ajaxStart(function () {
  4.         $('#fileUploadBox').val('Uploading...');
  5.         $('#fileUploadBox').addClass('loadinggif');
  6.     }).ajaxComplete(function () {
  7.         $('#fileUploadBox').removeClass('loadinggif');
  8.     });
  9.     $.ajaxFileUpload({
  10.         url: '/GenericHandlers/AjaxFileUploader.ashx',
  11.         secureuri: false,
  12.         fileElementId: 'fileToUpload',
  13.         dataType: 'json',
  14.         data: { name: 'logan', id: 'id' },
  15.         success: function (data, status) {
  16.             if (typeof (data.error) != 'undefined') {
  17.                 if (data.error != '') {
  18.                     //alert(data.error);
  19.                 } else {
  20.                     $('#fileUploadBox').val(data.msg);
  21.                     $("#hdnFilePath").val(data.path + "?" + data.msg);
  22.                 }
  23.             }
  24.         },
  25.         error: function (data, status, e) {
  26.             //alert(e);
  27.             $('#fileUploadBox').val('File size is too large.');
  28.         }
  29.     });
  30.     $.extend({
  31.         handleError: function (s, xhr, status, e) {
  32.             if (s.error)
  33.                 s.error(xhr, status, e);
  34.             else if (xhr.responseText)
  35.                 console.log(xhr.responseText);
  36.         }
  37.     });
  38.     return false;
  39. }
  40. </script>
Source: Hayageek
Tuesday, 21 January 2014
Posted by Jebastin

How to Remove the white spaces at the start and end of the string?

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>jQuery.trim demo</title>
  6. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  7. </head>
  8. <body>
  9. <pre id="original"></pre>
  10. <pre id="trimmed"></pre>
  11. <script>
  12. var str = "     lots of spaces before and after     ";
  13. $( "#original" ).html( "Original String: '" + str +"'");
  14. $( "#trimmed" ).html( "Trimmed String: '" + $.trim(str) +"'");
  15. </script>
  16. </body>
  17. </html>
Posted by Jebastin
Tag : ,

How to Limit the number of characters allowed in form input text field?

By using the following attribute we can easily limit the number of characters allowed in form input text field.
maxlength="10"
Adding this attribute to your control:
<input type="text"
    id="txtPhone"
    name="Phone"
    maxlength="10" />
Posted by Jebastin
Tag :

How to get the Created & last Published date of a Node in Umbraco?

Using the following CSHTML code we can easily get the Created & last Published date of a Node in Umbraco.
To get the Created Date of an Umbraco Node:
  1. @Model.CreateDate
To get the Last Published Date of an Umbraco Node:
  1.  @Model.UpdateDate
Posted by Jebastin

How to get the value of a CSS property using jQuery?

Consider the following HTML:
  1. <div id="jjTechSol" style="height: 50px;width: 50px;">
  2.  <p>Content</p>
  3.  </div>
The following jQuery is used to get the value of a CSS property.
  1. <script type="text/javascript">
  2. $(document).ready(function () {
           alert('Height:'+$("#jjTechSol").css('height'));
  3.        alert('Width:'+$("#jjTechSol").css('width'));
    });
  4. </script> 
.css( propertyName ) gets the value of style properties for the first element in the set of matched elements.
     propertyName
     Type: String    
     A CSS property.
Wednesday, 15 January 2014
Posted by Jebastin
Tag : ,

How to Compare two fields with jQuery validate plugin?


Consider the following HTML.
  1. <input type="text" id="txtEmail" name="Email"  />
  2. <input type="text" id="txtConfirmEmail" name="ConfirmEmail" /> 
The following script is used to Compare two fields with jQuery validate plugin.
  1. $('#myform').validate({
  2.     rules: {
  3.         Email: { required: true },
  4.         ConfirmEmail: { equalTo: '#txtEmail' }
  5.     }
  6. });
Wednesday, 8 January 2014
Posted by Jebastin

How to convert the first character of a string into upper case?

The following C# code is used to convert the first character of a string into upper case.
  1. static string UppercaseFirst(string s)
  2. {
  3. // Check for empty string.
  4. if (string.IsNullOrEmpty(s))
  5. {
  6.     return string.Empty;
  7. }
  8. // Return char and concat substring.
  9. return char.ToUpper(s[0]) + s.Substring(1);
  10. }
Tuesday, 7 January 2014
Posted by Jebastin
Tag :

Link To This Post/Page

Spread The Word

Add this button to your blog:
JJ Technology Solutions

Blog Archive

Trackers

eXTReMe Tracker
facebook

- Copyright © JJ Technology Solutions - Powered by Source Code Solutions -