一、引入js文件
<script type="text/javascript" src="/Scripts/JQuery.min.js"></script>
<script src="/scripts/AjaxUpload.3.5.js" type="text/javascript"></script>
二、Upload.ashx代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.IO;
using System.Globalization;
using LitJson;
using System.Web.SessionState;
namespace HuWaiTong.Ashx
{
/// <summary>
/// UploadFile 的摘要说明
/// </summary>
public class Upload : IHttpHandler, IRequiresSessionState
{
private HttpContext context;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//指定文件保存目录
string getPath = context.Request.QueryString["p"] ;
//文件保存目录路径
string savePath = "/upload/" + getPath + "/";
//文件保存目录URL
string saveUrl = "/upload/" + getPath + "/";
//定义允许上传的文件扩展名
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
extTable.Add("flash", "swf,flv");
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,amr,rm,rmvb");
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,css");
//最大文件大小
string dirName = context.Request.QueryString["dir"];
int maxSize = 1000000;
if (dirName == "media")
{
maxSize = 4000000;
}
this.context = context;
HttpPostedFile imgFile = context.Request.Files["imgFile"];
if (imgFile == null)
{
showError("请选择文件。");
}
string dirPath = context.Server.MapPath(savePath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (string.IsNullOrEmpty(dirName))
{
dirName = "image";
}
if (!extTable.ContainsKey(dirName))
{
showError("目录名不正确。");
}
string fileName = imgFile.FileName;
string fileExt = Path.GetExtension(fileName).ToLower();
if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
{
showError("上传文件大小超过限制。");
}
if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
{
showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
}
//创建文件夹
dirPath += dirName + "/";
saveUrl += dirName + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string ymdStr = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
dirPath += ymdStr + "/";
saveUrl += ymdStr + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
string filePath = dirPath + newFileName;
imgFile.SaveAs(filePath);
string fileUrl = saveUrl + newFileName;
Hashtable hashMsg = new Hashtable();
hashMsg["error"] = 0;
hashMsg["url"] = fileUrl;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
//转相对路径
//2013-11-29 11:17:46
if (!string.IsNullOrEmpty(context.Request["relative"]))
{
var relativeUrl = hashMsg["url"].ToString().Substring(0, hashMsg["url"].ToString().IndexOf("upload"));
hashMsg["url"] = hashMsg["url"].ToString().Replace(relativeUrl, "../../../");
}
context.Response.Write(JsonMapper.ToJson(hashMsg));
context.Response.End();
}
private void showError(string messageStr)
{
Hashtable hashMsg = new Hashtable();
hashMsg["error"] = 1;
hashMsg["message"] = messageStr;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hashMsg));
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
三、使用
脚本
<script>
new AjaxUpload($("#upload_id"), {
action: '/Ashx/Upload.ashx?p=page&dir=image',
name: 'imgFile',
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
$.messager.alert('错误提示', '只能上传 JPG, PNG 或 GIF 类型的文件!', 'info');
return false;
}
},
onComplete: function (file, response) {
response = eval("(" + response + ")");
if (response.error != "0") {
alert(response.message);
} else {
document.getElementById("#show_id").setAttribute("src", response.url);
document.getElementById("#value_id").setAttribute("value", response.url);
}
}
});
</script>
html代码
<img id="show_id" src="" >
<input id="value_id" value="" type="hidden">
<a id="upload_id" ">选择图片</a>