Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

jQuery Ajax Upload File into ASP.NET without FileUploadControl

Summary

A simple way to upload file into ASP.NET server is to use FileUploadControl. However, this is not very flexible. You may not have multiple upload controls. In this article, we will use the more flexible jQury/Ajax upload method on client side and ASP.NET HttpHandler on the serverside.

Html file

<div />Choose file: <input type="file" id="file" style="width:360px" /> <input type="button" onclick="uploadFile()" value="Upload"" /> </div>

javascript code
function uploadFile() {
   // File validaton
   if ($('#file')[0].files.length == 0) {
      alert("Please choose a png or jpg pciture.");
      return;
   }
   var file = $('#file')[0].files[0];
   var fname = file.name.toLowerCase();
   if (fname.indexOf(".png") < 0 && fname.indexOf(".jpg") < 0) {
      alert("Invalid image type, jpg or png file only.");
      return;
   }
   // Send file
   var formData = new FormData();
   formData.append('file', file);
   $.ajax({
      url: "FileLoad.ashx",
      type: 'POST',
      complete: function () { },
      progress: function (evt) { },
      success: function (e) {
         alert("Picture upload success.");
      },
      error: function (e) { alert("Upload failed."); },
      data: formData,
      cache: false,
      contentType: false,
      processData: false
   });
}
Extra parameters could be passed in url with query string, for example,
url: "FileLoad.ashx?dir=data&action=1"

Serverside FileLoad.ashx

<%@ WebHandler Language="C#" Class="FileLoad" %>
using System;
using System.Web;

public class FileLoad : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
      // Get query string, if any     
      NameValueCollection nvc = context.Request.QueryString;
      // Can be more than 1 files
      foreach (string f in context.Request.Files.AllKeys)
      {
         HttpPostedFile file = context.Request.Files[f];
         if (!String.IsNullOrEmpty(file.FileName))
         {
            string fpath = context.Request.MapPath(context.Request.ApplicationPath) + "/";
            file.SaveAs(fpath1 + file.FileName);
         }
      }
      context.Response.ContentType = "text/plain";
      context.Response.Write("ok");
   }
}
Ads from Google
Dr Li Anchor Profi
www.anchorprofi.de
Engineering anchorage plate design system
©Andrew Qu, 2015. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.