首先从网上下载一个ajaxupload.3.6.js
也可以我的资源下载 ajaxupload.3.6.js
SCRIPT
<script type="text/javascript" src="Js/jquery.js"></script>
<script type="text/javascript" src="Js/ajaxupload.3.6.js"></script>
<script type="text/javascript">
$(document).ready(function() {
HiddenControl();
/* example 2 */
new AjaxUpload('#button_upload', {
//action: 'upload.php',
action: 'Ashx/AjaxUpload.ashx', // I disabled uploads in this example for security reaaons
onSubmit: function(file, ext) {
//if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)) {
/* Setting data */
this.setData({
'key': 'This string will be send with the file'
});
} else {
//文件格式不正确
return false;
}
},
onComplete: function(file, response) {
var filename = response.replace(/<[^>].*?>/g, ""); //获取后台上传文件名,源文件名是file
$('#<%=hidden_ImgUrl.ClientID %>').val(filename); //赋值给hidden,以便后台获取
ShowControl();
}
});
}); </script>
HTML
<input id="button_upload" class="form_button_big" type="button" value="本地上传" style="margin-bottom: 8px;" />
<asp:HiddenField ID="hidden_ImgUrl" runat="server" />
<img id="img_UploadPicture" src="" οnlοad="DrawImage(this, '269', '269');" />
AjaxUpload.ashx
<%@ WebHandler Language="C#" Class="AjaxUpload" %>
using System;
using System.Web;
using System.Text;
using BLL;
using System.IO;
using Common;
public class AjaxUpload : IHttpHandler
{
#region 属性
private B_YP_Members _Member = new B_YP_Members();
#endregion
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request.ServerVariables["HTTP_REFERER"] == null)
{
context.Response.Write("不要这样访问");
context.Response.End();
}
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fullFileName = GetFileName() + strExtension;
string strSaveLocation = context.Server.MapPath("~/UploadFile/Img/") + fullFileName;
context.Request.Files[0].SaveAs(strSaveLocation);
context.Response.Write(fullFileName);
context.Response.Flush();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
private string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmss"));
serial.Append(rd.Next(100000, 999999).ToString());
return serial.ToString();
}
}