引入jQuery庫
引入ajaxfileupload.js上傳插件庫(這也是jQuery的一個插件)
以ASP.NET為例
<input type="file" id="uploadfile" name="uploadfile"/>
<script type="text/javascript">
$("#uploadfile").change(function(){
$.ajaxFileUpload({
url: '../ajax/AjaxCallback.ashx',//處理上傳用的后台程序,可以是PHP,也可以是ASP等
secureuri: false,//異步
fileElementId: 'uploadfile',//上傳控件ID
dataType: 'json',//返回的數據信息格式
success: function(data, status) {
if (data.code == '10000') {
alert("上傳成功");
} else {
alert("上傳失敗");
}
}, error: function(data, status, e) {
alert(e);
}
})
});
</script>
后台CS代碼
/// <summary>
/// 圖片上傳
/// </summary>
private void ImageUpload()
{
Response.ContentType = "text/html";//這里一定要html
if (Request.Files.Count > 0)
{
HttpPostedFile file = Request.Files[0];
if (file.ContentLength > 0)
{
string suffix = file.FileName.Substring(file.FileName.LastIndexOf('.'));//后綴
if (".jpg.png.gif.jpeg".IndexOf(suffix.ToLower()) == -1)//文件格式,這里采用圖片格式說明
{
Response.Write("{\"msg\":\"文件格式不正確!\",code:\"10001\"}");
return;
}
try
{
file.SaveAs(Server.MapPath("~/uploadfile/") + newName);
Response.Write("{\"msg\":\"" + newName + "\",code:\"10000\"}");
return;
}
catch (Exception ex)
{
Response.Write("{\"msg\":\"" + HttpUtility.HtmlEncode(ex.Message) + "\",code:\"10001\"}");
return;
}
}
Response.Write("{\"msg\":\"請選擇要上傳的文件!\",code:\"10001\"}");
return;
}
Response.Write("{\"msg\":\"請選擇要上傳的文件!\",code:\"10001\"}");
return;
}
http://www.cnblogs.com/linjiqin/p/3530848.html
http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
http://www.phpletter.com/cn/Demo/AjaxFileUpload-Demo/