ajax上传文件的原理与实现

前端之家收集整理的这篇文章主要介绍了ajax上传文件的原理与实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

转载,JS实现上传看得不多,.NET直接拖控件太LOW

http://blog.csdn.net/xuexiaodong009/article/details/45556431

ajax已经很普遍了,但使用ajax上传文件自己却一直都没有涉及,我只知道挺复杂的,上传文件不同于上传一般的表单数据,必须特殊处理,知道一般ajax使用上传都是应用一个虚拟的iframe,但由于项目需要,在网上找了找,没想到找到了两个支持ajax上传文件的jquery插件,jquery.uploadify.js和dropzone.min.js两个都可以实现ajax上传文件效果也不错。


1使用jquery.uploadify.js上传文件

这种上传方式,使用了Flash,因此需要引用一个特殊的js文件swfobject.js,低版本的需要引用,高版本的这个文件已经包含在jquery.uploadify.js中了。另外低版本的参数和高版本的参数也不太一样了。

使用Uploadify v3.2.1的完整前台代码

[html] view plain copy
  1. <htmlxmlns="http://www.w3.org/1999/xhtml">
  2. headrunat="server">
  3. title></scriptsrc="Scripts/jquery-1.8.0.min.js"type="text/javascript"scriptscriptsrc="Styles/jquery.uploadify.js"type="text/javascript"linkhref="Styles/uploadify.css"rel="stylesheet"type="text/css"/>
  4. scripttype="text/javascript" $(document).ready(function(){
  5. $("#uploadify").uploadify({
  6. swf:'Styles/uploadify.swf',
  7. uploader:'Handler1.ashx?OperationType=upfile',//后台的处理地址
  8. fileTypeDesc:'请选择excel文件',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> buttonText:'请选择excel文件',
  9. fileTypeExts:'*.xls',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'auto':false,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> onSelectError:function(file,errorCode,errorMsg){
  10. switch(errorCode){
  11. case-100:
  12. alert("上传文件数量已经超出系统限制的"+$('#uploadify').uploadify('settings','queueSizeLimit')+"个文件!");
  13. break;
  14. case-110:
  15. alert("文件["+file.name+"]大小超出系统限制的"+$('#uploadify').uploadify('settings','fileSizeLimit')+"大小!");
  16. break;
  17. case-120:
  18. alert("文件["+file.name+"]大小异常!");
  19. case-130:
  20. alert("文件["+file.name+"]类型不正确!");
  21. }
  22. },108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> onFallback:function(){
  23. alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
  24. },248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //上传到服务器,服务器返回相应信息到data里
  25. onUploadSuccess:function(file,data,response){
  26. alert(data);
  27. onSelect:function(fileObj){
  28. alert("文件名:"+fileObj.name+"\r\n"+
  29. "文件大小:"+fileObj.size+"\r\n"+
  30. "创建时间:"+fileObj.creationdate+"\r\n"+
  31. "最后修改时间:"+fileObj.modificationdate+"\r\n"+
  32. "文件类型:"+fileObj.type
  33. );
  34. });
  35. });
  36. functiondoUplaod(){
  37. $('#uploadify').uploadify('upload','*');
  38. }
  39. functioncloseLoad(){
  40. $('#uploadify').uploadify('cancel',0); background-color:inherit; font-weight:bold">headbodyformid="form1"runat="server"divdivid="fileQueue"inputtype="file"name="uploadify"id="uploadify"pahref="javascript:doUplaod()">上传a>|
  41. ahref="javascript:closeLoad()">取消上传formhtml>


Uploadify v2.1.0的写法

由于没有swfobject.js,需要添加引用

    scriptsrc="Scripts/swfobject.js"type="text/javascript">
另外部分参数也不一样,例如uploader,script

完整的前台代码

    scriptsrc="Scripts/jquery.uploadify.v2.1.0.js"type="text/javascript"
  1. linkhref="Scripts/uploadify.css"rel="stylesheet"type="text/css"/>
  2. $("#uploadify").uploadify({
  3. 'uploader':'Scripts/uploadify1.swf',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'script':'Handler1.ashx?OperationType=upfile',
  4. 'cancelImg':'Scripts/cancel.png',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'folder':'UploadFile',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'queueID':'fileQueue',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'auto':false,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'multi':false,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'fileExt':'*.doc;*.xls',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'fileDesc':'请选择excel文件',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> 'onSelect':function(e,queueId,fileObj){
  5. alert("唯一标识:"+queueId+"\r\n"+
  6. "文件名:"+fileObj.name+"\r\n"+
  7. "文件大小:"+fileObj.size+"\r\n"+
  8. "创建时间:"+fileObj.creationDate+"\r\n"+
  9. "最后修改时间:"+fileObj.modificationDate+"\r\n"+
  10. "文件类型:"+fileObj.type
  11. );
  12. ahref="javascript:$('#uploadify').uploadifyUpload()"ahref="javascript:$('#uploadify').uploadifyClearQueue()">

2使用dropzone.min.js上传文件

没有使用Flash,但对浏览器要求比较高,例如IE10以上才支持,应该是使用了html5的技术

完整的前端代码

    scriptsrc="Scripts/dropzone.min.js"type="text/javascript"linkhref="Scripts/dropzone.css"rel="stylesheet"type="text/css" jQuery(function($){
  1. Dropzone.autoDiscover=false;
  2. try{
  3. varmyDropzone=newDropzone("#dropzone",{
  4. paramName:"FileData",//Thenamethatwillbeusedtotransferthefile
  5. maxFilesize:5,//MB
  6. dictRemoveFile:'移除文件',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictCancelUpload:'取消上传',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> addRemoveLinks:true,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> uploadMultiple:false,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> acceptedFiles:'.xls',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> autoProcessQueue:true,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictRemoveFile:"关闭",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictFileTooBig:'此文件过大',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictCancelUploadConfirmation:'确定取消上传吗?',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictInvalidInputType:"不支持此类型文件上传!",248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> parallelUploads:1,//限制上传文件
  7. url:"Handler1.ashx?OperationType=upfile",248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> init:function(){
  8. this.on("success",function(file){
  9. //console.log("File"+file.name+"uploaded");
  10. alert("文件"+file.name+"上传成功");
  11. this.on("complete",248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> this.removeFile(file);
  12. this.on("removedfile",function(file){
  13. //alert(file.name);
  14. /*accept:function(file,done){
  15. //if(file.name=="11.jpg"){
  16. //done("Naha,youdon't.");
  17. //}
  18. //else{
  19. done();
  20. success:function(file,data){
  21. if(data.status===1){
  22. $scope.uploadImage=data.message;
  23. $scope.listUserImages();
  24. }else{
  25. //alertService.showAlert({
  26. //content:data.message,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //type:'warning'
  27. //});
  28. //$('.dz-error-mark').show();
  29. //alert(data.message);
  30. dictDefaultMessage:
  31. 'spanclass="bigger-150bolder"iclass="ace-iconfafa-caret-rightred"ispan>文件\spanclass="smaller-80grey">点击>br/>\iclass="upload-iconace-iconfafa-cloud-uploadbluefa-3x">',248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> dictResponseError:'Errorwhileuploadingfile!',108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //changethepreviewTemplatetouseBootstrapprogressbars
  32. previewTemplate:"divclass=\"dz-previewdz-file-preview\">\ndivclass=\"dz-details\"divclass=\"dz-filename\"spandata-dz-namedivclass=\"dz-size\"data-dz-sizeimgdata-dz-thumbnail/>\ndivclass=\"progressprogress-smallprogress-stripedactive\"divclass=\"progress-barprogress-bar-success\"data-dz-uploadprogressdivclass=\"dz-success-mark\"divclass=\"dz-error-mark\"divclass=\"dz-error-message\"spandata-dz-errormessage>"
  33. }catch(e){
  34. alert('Dropzone.jsdoesnotsupportolderbrowsers!');
  35. formid="dropzone"runat="server"action="Handler1.ashx?OperationType=upfile"class="dropzonedz-clickable"enctype="multipart/form-data"method="post"divclass="dz-message"style="width:50px;height:50px;"divid="FileBed">点击上传文件
  36. inputtype="file"multiple="multiple"class="dz-hidden-input"style="visibility:hidden;position:absolute;top:0px;left:0px;height:0px;width:0px;">

3后台处理代码

[csharp]
    publicclassHandler1:IHttpHandler
  1. {
  2. voidProcessRequest(HttpContextcontext)
  3. {
  4. stringoperatype=context.Request.QueryString["OperationType"];
  5. if(operatype=="upfile")
  6. HttpPostedFilefile=context.Request.Files["FileData"];
  7. if(file!=null)
  8. stringfullPath=System.IO.Path.Combine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"update"),DateTime.Now.Date.ToString("yyyyMMdd"));
  9. file.SaveAs(fullPath+file.FileName);
  10. context.Response.ContentType="text/plain";
  11. context.Response.Write("上传成功");
  12. boolIsReusable
  13. get
  14. returnfalse;
  15. }

猜你在找的Ajax相关文章