<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="jquery-1.8.2.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script> <script type="text/javascript"> function ajaxFileUpload() { $("#loading").ajaxStart(function () { $(this).show(); }).ajaxComplete(function () { $(this).hide(); }); $.ajaxFileUpload({ url: '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 { alert(data.msg); } } }, error: function (data, status, e) { alert(e); } }); return false; } </script> </head> <body> <form id="form1" runat="server" enctype="multipart/form-data"> <div> <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"> <button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button> <img id="loading" name='loading' src="loading.gif" style="display:none;"> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace JuqeryFileUPload { /// <summary> /// Summary description for AjaxFileUploader /// </summary> public class AjaxFileUploader : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.Files.Count > 0) { string path = context.Server.MapPath("~/image"); 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 += "}"; context.Response.Write(msg); } } public bool IsReusable { get { return true; } } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)