javascript与asp.net实现文件上传

1 篇文章 0 订阅
1 篇文章 0 订阅

方法一:使用FileUpLoad 控件多个直接上传。这样做的问题就是要求页面提交,从而导致一些不应该刷新的内容在此操作过程中消失掉。但是用ScriptManger 来弄 却又不能上传了 原因很简单 FileUpLoad 控件要求post。由于这个问题 所以多数人都很少采用这种方法,不得不另寻它法。下面的方法二解决此问题。

方法二:使用Html标签<input type="file"/> + form 的submit来实现。我们一边实现文件上传都会对文件有些说明,文件放在服务器硬盘上,但信息确是放在数据库中,所以这种方法 就会导致这两部分信息的存储问题。不过这种方法总是比方法一可取,我们可在讲多文件的信息一一提交 一一保存。对于在最后提交文件其他信息的时候才提交文件 这样减少了对文件控制(如果先提交文件,但最后用户并没有选择提交文件的其他的信息,这是由需要上传上传的文件,这样就带了很多其他的问题,而且操作也不符合用户操作)。所以都想先将要上传的文件选择好到最后的时候一起的提交,如果最终用户没有提交,那也不用再进行文件从服务器上删除的那一步操作了,这样减少了很多操作和其他问题,也是我正想要的效果。

 

方法三:就是使用js +Ajax 来实现,测试过好像不行,因为我们上传文件的时候需要设置enctype="multipart/form-data",这样测试过导致文件的其他信息咋服务器端获取不到,测试过一次也不知道是自己弄错没。

方法四:在方法二的延伸,如果自己的上传是单独分开的。可以使用flex的上传,外观比较好。

同时与方法二可以调用同一后台上传文件处理程序。

方法二的例子如下:

使用了prototype.js架构

js 部分

var Bind = function(object, fun) {
return function() {
   return fun.apply(object, arguments);
}
}

var Each = function(list, fun){
for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
};
var Extend = function(destination, source) {
for (var property in source) {
   destination[property] = source[property];
}
}
var FileUpload=Class.create();
FileUpload.prototype={
   
    initialize:function(folder,hiddenId,options){
        this.Folder=document.getElementById(folder)? document.getElementById(folder):document.body;
        this.Hidden=document.getElementById(hiddenId);
        this.Files=[];
       
        this.SetOptions(options);
        this.FileNamePreFix=this.options.FileNamePreFix;
        this.FileCount=this.options.FileCount;
        this.FileMax=this.options.FileMax;
        this.FileExtIn=this.options.FileExtIn;
        this.AllowSame=this.options.AllowSame;
       
        this.onIniFile=this.options.onIniFile;
        this.onEmpty=this.options.onEmpty
        this.onLimitMax=this.options.onLimitMax;
        this.onLimitFileExtIn=this.options.onLimitFileExtIn;
        this.onSame=this.options.onSame;
        this.onFail=this.options.onFail;
        this.onInit=this.options.onInit;
       
        this.InitFile();
    },
    options:{
        FileNamePreFix:"File_",//file控件名前缀
        FileCount:0,//文件个数,默认是0
        onIniFile:function(){},
        onEmpty:function(){},
        FileMax:3,//最多上传文件数 3+1个
        onLimitMax:function(){},
        FileExtIn:[],//文件扩展名数组
        onLimitFileExtIn:function(){},//文件扩展名处理函数
        AllowSame:true,//允许上传同名文件
        onSame:function(){},//同名文件处理函数
        onFail:function(){},//文件检测不符合上传文件要求的处理函数
        onInit:function(){}//初始化函数
    },
    SetOptions:function(options){
        Extend(this.options,options || {});
    },
    InitFile:function(){
        this.Files=[];
        Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){
   if(o.type == "file"){ o.value && this.Files.push(o); this.onIniFile(o); }
     }))
        var file=document.createElement('input');
        file.name=this.FileNamePreFix+this.FileCount;
        file.type= 'file';
        file.οnchange=Bind(this,function(){this.Check(file);this.InitFile();});
        this.Folder.appendChild(file);
        this.FileCount++;
        this.onInit();
    },
    InitPicControl:function(){
        var picArray=[];
        for(var i=0;i<this.Files.length;i++){
          var unit=new bbsPictureUnit(this.Files[i].name,this.Files[i].value,'','');
          picArray.push(unit);
        }
        new bbsPictureCtrl(picArray,'picShowContainer');
    },
    Check:function(file){
        var isCheck=true;
        var value=file.value;
        if(!value){
          isCheck=false;
          this.onEmpty();
        }
        else if(this.FileMax && this.Files.length>this.FileMax){
            isCheck=false;
            this.onLimitMax();
        }
        else if(this.FileExtIn.length && !RegExp("/.(" + this.FileExtIn.join("|") + ")$", "i").test(file.value)){
           isCheck=false;
           this.onLimitFileExtIn();
        }
        else if(!this.AllowSame){
           Each(this.Files,function(o){
              if(o.value==value){
                 isCheck=false;
              }
           });
           if(!isCheck){
              this.onSame();
           }
        }
        if(!isCheck){
          this.onFail(file);
        }
        else{
           var title=document.getElementById('txtPicTitle').value;
           var explain=document.getElementById('txtPicExp').value;
           this.Hidden.value +=file.name+"="+title+","+explain+";";
        }
    },
    Delete:function(file){
      if(this.Hidden.value.length>0){
            var fileInfo=this.Hidden.value.split(';');
            var cloneFileInfo=[];
            var n=0;
            for(var i=0;i<fileInfo.length;i++){
                if(fileInfo[i].indexOf(file.name)==-1){
                   cloneFileInfo[n++]=fileInfo[i];
                }
            }
            fileInfo=cloneFileInfo;
            this.Hidden.value=this.ArrayToString(fileInfo);
        }    
        this.Folder.removeChild(file);
        this.InitFile();
    },
    Clear:function(){
        Each(this.Files,Bind(this, function(o){this.Folder.removeChild(o);}));
        this.Hidden.value="";
        this.InitFile();
    },
    ArrayToString:function(arr){
       var str="";
       if(arr.length<1){
           return str;
       }
       else{
         for(var i=0;i<arr.length;i++){
           str+= arr[i]+";";
         }
         return str;
       }
    }
};
function AddRows(rows){
    //根据数组来添加列表
var FileList = $("idFileList"), oFragment = document.createDocumentFragment();
//用文档碎片保存列表
Each(rows, function(cells){
   var row = document.createElement("tr");
   Each(cells, function(o){
    var cell = document.createElement("td");
    if(typeof o == "string"){ cell.innerHTML = o; }else{ cell.appendChild(o); }
    row.appendChild(cell);
   });
   oFragment.appendChild(row);
})
//ie的table不支持innerHTML所以这样清空table
while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); }
FileList.appendChild(oFragment);
}

asp.net部分:

<table border="0" cellspacing="1" class="fu_list">
           <thead>
                 <tr>
                   <td colspan="2"><b>上传文件</b></td>
                 </tr>
           </thead>
           <tbody>
                  <tr>
                      <td align="right" width="15%" style="line-height:35px;">添加文件:</td>
                        <td align="left"><a href="javascript:void(0);" class="files" id="idFile"></a></td>
                       <td>标题:<input id="txtPicTitle" type="text" value="标题" maxlength="20"/>说明:<input id="txtPicExp" type="text" value="说明" maxlength="20" />
                      </td>
                </tr>
                     <tr>
                    <td colspan="3"><table border="0" cellspacing="0">
                       <thead>
                          <tr>
                           <td>文件路径</td>
                            <td width="100"></td>
                           </tr>
                          </thead>
                          <tbody id="idFileList">
                                      
                          </tbody>
                        </table></td>
                     </tr>
                       <tr>
                           <td colspan="3" style="color:gray">温馨提示:最多可同时上传 <b id="idLimit"></b> 个文件,只允许上传 <b id="idExt"></b> 文件。 </td>
                        </tr>
                          <tr>
                            <td colspan="3" align="center" id="idMsg">
                                  
                         </td>
                          </tr>
                          <tr>
                          <td id="picShowContainer" colspan="3" align="center">图片预览
                                   
                            </td>
                    </tr>
               </tbody>
           </table>    

<asp:HiddenField ID="hdValue" runat="server" />
       <script language="javascript" type="text/javascript">
        var fu=new FileUpload('idFile','hdValue',{FileExtIn:['jpg','gif','png','bmp','JPG','GIF','PNG','BMP'],AllowSame:false,
            onIniFile: function(file){ file.value ? file.style.display = "none" : this.Delete(file); },
         onEmpty: function(){ alert("请选择一个文件"); },
         onLimitMax: function(){ alert("超过文件上传最大限制"); },
         onSame: function(){ alert("已经有相同文件"); },
         onLimitFileExtIn: function(){ alert("只允许上传" + this.FileExtIn.join(",") + "文件"); },
         onFail: function(file){this.Delete(file);return false; },
         onInit: function(){
          //显示文件列表
          var arrRows = [];
          if(this.Files.length){
           var oThis = this;
           Each(this.Files, function(o){
            var a = document.createElement("a"); a.innerHTML = "取消上传"; a.href = "javascript:void(0);";
            a.onclick = function(){ oThis.Delete(o); return false; };
            arrRows.push([o.value, a]);
           });
          } else { arrRows.push(["<font color='gray'>没有添加文件</font>", "&nbsp;"]); }
          AddRows(arrRows);
          this.InitPicControl();
         }
        });
        $("idLimit").innerHTML = fu.FileMax+1;

        $("idExt").innerHTML = fu.FileExtIn.join(",");                        
     </script>                        

C#获取文件部分 使用HttpFileCollection,HttpPostedFile

List<BBSPictureUnit> bbsPictureList = new List<BBSPictureUnit>();
            HttpFileCollection httpFileCollection = Request.Files;
            int fileTotal = httpFileCollection.Count;
            if(fileTotal>0)
            {
                string[] titleExp = hdValue.Value.Split(';');

                for (int i = 0; i < fileTotal-1; i++)
                {
                    HttpPostedFile file = httpFileCollection[i];
                    if(string.IsNullOrEmpty(file.FileName))
                    {
                        continue;
                    }
                    string thisFileInfo = titleExp[i];
                    string filPath = GetUpLoadPicturePath(file.FileName);
                    file.SaveAs(filPath);
                    BBSPictureUnit bbsPictureUnit = new BBSPictureUnit();
                    bbsPictureUnit.PictureId = SequenceBLD.GetSequence(BBSConst.TGISBBS_PICTURE);
                    bbsPictureUnit.ContentId = bbsContentUnit.ID;
                    bbsPictureUnit.PictureTitle = string.IsNullOrEmpty(thisFileInfo) ? "标题" : thisFileInfo.Split('=')[1].Split(',')[0];
                    bbsPictureUnit.PictureExplain = string.IsNullOrEmpty(thisFileInfo) ? "说明" : thisFileInfo.Split('=')[1].Split(',')[1];
                    bbsPictureUnit.PicturePath = filPath.Replace("//", "/");
                    bbsPictureList.Add(bbsPictureUnit);
                }
            }

同时把要上传的图片预览:

var bbsPictureUnit=Class.create();
bbsPictureUnit.prototype={

        initialize:function(pictureId,picturePath,pictureTitle,pictureExplain)
        {
           this.pictureId=pictureId;
           this.picturePath=picturePath;
           this.pictureTitle=pictureTitle;
           this.pictureExplain=pictureExplain;
        }
};

var bbsPictureCtrl=Class.create();
bbsPictureCtrl.prototype={

        initialize:function(picArray,parentId)
        {
            this.picArray=picArray;
            this.parentId=parentId;
            this.createCtrl();
        },
        createCtrl:function()
        {
              var div=document.getElementById(this.parentId+"_pic");
              if(div){
                 div.parentNode.removeChild(div);
              }
              var div=document.createElement('div');
              div.id=this.parentId+"_pic";
              div.align="left";
              div.style.border="solid 0px ";
              var html=this.getPicHtml();
              div.innerHTML=html;
              var parentObj=document.getElementById(this.parentId);
              parentObj.appendChild(div);
              Event.observe(div,'click',this.imgOnClick.bindAsEventListener(this));
        },
        getPicHtml:function()
        {
            if(this.picArray.length>0)
               {
                    var html='<table cellpadding="0" cellspacing="6" class="picTable"><tr>';
                    html+='<td width="120px" align="center" valign="middle">';
                    html+='<div class="picCtrlIndex">';
                    for(var i=0;i<this.picArray.length;i++)
                      {
                         var img=document.createElement('img');
                         img.id=this.parentId+'_img_'+i;
                         img.src=this.picArray[i].picturePath;
                         img.alt=this.picArray[i].pictureTitle;
                         img.className='picture';
                         img.setAttribute('picTitle',this.picArray[i].pictureTitle);
                         img.setAttribute('explian',this.picArray[i].pictureExplain);
                         html+=img.outerHTML;
                      }
                   html+='</div></td>'
                       +'<td align="center" valign="top"><div id="'+this.parentId+'_picTitle">'+this.picArray[0].pictureTitle+'</div><img class="picCtrl" id="'+this.parentId+'_picCtrl" src="'+this.picArray[0].picturePath+'" /><div id="'+this.parentId+'_picExplain">'+this.picArray[0].pictureExplain+'</div></td></tr></table>';
                   return html;
               }
               else{
                  return "";
               }
        },
        imgOnClick:function(e)
        {
           var obj=Event.element(e);
           if(!obj) { return;}
           if(obj.id.indexOf('_img_')>-1)
           {
                document.getElementById(this.parentId+'_picTitle').innerText=obj.getAttribute('picTitle');
                document.getElementById(this.parentId+'_picExplain').innerText=obj.getAttribute('explian');
                document.getElementById(this.parentId+'_picCtrl').src=obj.src;
                obj.style.border="solid 4px #ff0000";
                var parnetObj=obj.parentNode;
                var len=parnetObj.childNodes.length;
                if(len>0)
                {
                    for(var i=0;i<len;i++)
                    {
                       var child=parnetObj.childNodes[i];
                       if(child.id!=obj.id)
                       {
                         child.style.border="solid 0px ";
                       }
                    }
                }
           }
           else
           {
             return;
           }
        }
};
function picCtrlClick(parentId,picExplain,e)
{
if(parentId)
{
     document.getElementById(parentId+'_picTitle').innerText=e.alt;
     document.getElementById(parentId+'_picExplain').innerText=picExplain;
     document.getElementById(parentId+'_picCtrl').src=e.src;
     e.style.border="solid 4px #ff0000";
     var parnetObj=e.parentNode;
     var len=parnetObj.childNodes.length;
     if(len>0)
     {
        for(var i=0;i<len;i++)
        {
           var child=parnetObj.childNodes[i];
           if(child.id!=e.id)
           {
             child.style.border="solid 0px ";
           }
        }
     }
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值