自己动手打造ajax图片上传(网上没有的)
今天笔者需要一款图片上传插件,但是网上没有提供一款符合自己需求且好用的。于是就自己动手写了一个。
方法1,仅使用jquery代码,不用第三方插件。代码如下
<p>
<label>上传图片</label>
<inputclass="ke-input-text"type="text"id="url"value=""readonly="readonly"/>
<inputtype="button"id="uploadButton"value="Upload"/>
</p>
<scripttype="text/javascript">
$(function(){
$('.inp_fileToUpload').change(function(){
varformdata=newFormData();
varv_this=$(this);
varfileObj=v_this.get(0).files;
url="/upload/upload_json.ashx";
//varfileObj=document.getElementById("fileToUpload").files;
formdata.append("imgFile",fileObj[0]);
jQuery.ajax({
url:url,
type:'post',
data:formdata,
cache:false,
contentType:false,
processData:false,
dataType:"json",
success:function(data){
if(data.error==0){
v_this.parent().children(".img_upload").attr("src",data.url);
//$("#img").attr("src",data.url);
}
}
});
returnfalse;
});
});
</script>
这种方法的缺点:由于IE6\8\9\不支持formdata,所以这种方法不支持IE9及以下版本
方法二:使用ajaxfileupload.js插件
ajaxfileupload.js
html代码:
<p>
<label>ajax上传</label>
<inputtype="file"name="fileToUpload"id="fileToUpload"class="inp_fileToUpload"multiple="multiple"/>
<imgsrc="$web.site$web.tpl#**#adminht/images/lb_head.jpg"width="30px"height="30px"class="img_upload"id="img"/>
</p>
<p>
<label>最新修改人员:</label>
<inputreadonly="readonly"type="text"size="30"/>
</p>
<div>
<scripttype="text/javascript">
$(function(){
$(".inp_fileToUpload").live("change",function(){//现在这个已经适用于多个file表单。
ajaxFileUpload($(this).attr("id"),$(this).parent().children(".img_upload").attr("id"));
})
})
functionajaxFileUpload(file_id,img_id){
jQuery.ajaxFileUpload({
url:'/upload/upload_json.ashx',//用于文件上传的服务器端请求地址
secureuri:false,//是否需要安全协议,一般设置为false
fileElementId:file_id,//文件上传域的ID
dataType:'json',//返回值类型一般设置为json
success:function(data,status)//服务器成功响应处理函数
{
if(data.error==0){
$("#"+img_id).attr("src",data.url);
}else{
alert(data.message);
}
},
error:function(data,status,e)//服务器响应失败处理函数
{
alert(e);
}
})
returnfalse;
}
</script>
</div>
</div>
说明:这种方法目前测试支持IE8/9,谷歌,兼容比方法1好。建议采用方法2
文件上传后台处理代码(asp.net版)
<%@webhandlerLanguage="C#"class="Upload"%>
usingSystem;
usingSystem.Collections;
usingSystem.Web;
usingSystem.IO;
usingSystem.Globalization;
usingLitJson;
publicclassUpload:IHttpHandler
{
privateHttpContextcontext;
publicvoidProcessRequest(HttpContextcontext)
{
StringaspxUrl=context.Request.Path.Substring(0,context.Request.Path.LastIndexOf("/")+1);
//文件保存目录路径
StringsavePath="attached/";
//文件保存目录URL
StringsaveUrl=aspxUrl+"attached/";
//定义允许上传的文件扩展名
HashtableextTable=newHashtable();
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,rm,rmvb");
extTable.Add("file","doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
//最大文件大小
intmaxSize=1000000;
this.context=context;
HttpPostedFileimgFile=context.Request.Files["imgFile"];
if(imgFile==null)
{
showError("请选择文件。");
}
StringdirPath=context.Server.MapPath(savePath);
if(!Directory.Exists(dirPath))
{
showError("上传目录不存在。");
}
StringdirName=context.Request.QueryString["dir"];
if(String.IsNullOrEmpty(dirName)){
dirName="image";
}
if(!extTable.ContainsKey(dirName)){
showError("目录名不正确。");
}
StringfileName=imgFile.FileName;
StringfileExt=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);
}
Stringymd=DateTime.Now.ToString("yyyyMMdd",DateTimeFormatInfo.InvariantInfo);
dirPath+=ymd+"/";
saveUrl+=ymd+"/";
if(!Directory.Exists(dirPath)){
Directory.CreateDirectory(dirPath);
}
StringnewFileName=DateTime.Now.ToString("yyyyMMddHHmmss_ffff",DateTimeFormatInfo.InvariantInfo)+fileExt;
StringfilePath=dirPath+newFileName;
imgFile.SaveAs(filePath);
StringfileUrl=saveUrl+newFileName;
Hashtablehash=newHashtable();
hash["error"]=0;
hash["url"]=fileUrl;
context.Response.AddHeader("Content-Type","text/html;charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
}
privatevoidshowError(stringmessage)
{
Hashtablehash=newHashtable();
hash["error"]=1;
hash["message"]=message;
context.Response.AddHeader("Content-Type","text/html;charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
}
publicboolIsReusable
{
get
{
returntrue;
}
}
}