йվwww.cnzz.cn

˵

ˢϴ
Ҫʵļϴformüԣ
1.actionΪҪݵҳַ
2.methodΪ"post"
3.enctype/encodingΪ"multipart/form-data"Ҫעiejs޸formenctypeûЧģֻ޸encoding

Գʼʱã

this.Form.method = "post";
this.Form.encoding = "multipart/form-data";

Ҫעˢ²ajaxŶáϡiframe
ajaxύݱȻȡݣjsһ£ǲܲͻļҪȡļݾ͸˵ˣֻiframe
˵˵iframeʵˢϴԭformtargetԣύҳһͨΪصģiframeϡֱ۵˵ǰѡˢ¡iframe
ʵԭһiframeʵˢύһģֻﻻļ
ؼǰformtargetΪiframename

this.Form.target = this._FrameName;

iframe
ûԶiframeڳʼʱԶˢiframeġ
ȱѡһiframeˢʱǱģΪÿʵܴԵiframeһ

this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000);

Ҳһļ

ŴiframeΪdocument.createElement("iframe")nameԾˡ
ȴõnameieȻϣ˵nameֻԣҵһIE Ԫأһص㣬ǿͬһͬ
̬iframename

document.createElement("<iframe name=\"" + this._FrameName + "\">")
ʽffᱨ
uncaught exception: String contains an invalid character (NS_ERROR_DOM_INVALID_CHARACTER_ERR)
createElementʱܴname׼ӦҲԼݵķʽд

Code
var oFrame = isIE ? document.createElement("<iframe name=\"" + this._FrameName + "\">") : document.createElement("iframe");
//Ϊffname
oFrame.name = this._FrameName;
oFrame.style.display = "none";
ⷽϸ뿴

껹Ҫ뵽bodyУһʹdocument.body.appendChildieлСֹ󣬿δԣ

Code
<body>
<div>
<script>
document.body.appendChild(document.createElement("div"));
</script>
</div>
</body>
ҵһԭFFµʵֻǵҳ滹ûȫȡʱbodyԪؾѾˣIEֻҳȫȡbodyԪزŻڣҳвIE¾ͻִ󡱡
webδ֮ҲᵽʹinsertBefore棺


document.body.insertBefore(oFrame, document.body.childNodes[0]);
ڷļ꣨ʧܣ֮ô֪ͨͻأ
˵˵ҵķڿͻ˶һ

function Finish(msg){ alert(msg); location.href = location.href; }
ܼ򵥣ʾʾ¼ҳ棨ʹreloadᵼffiframeظݣ
Ƿ֪ͨͻ˵⣬iframeθҳ潻
ͨwindow.parentwindow.topiframeparenttopԡֱ𷵻ںϲȴڡ
ڷ˴֮

context.Response.Write("<script>window.parent.Finish('" + _msg + "');</script>");
ͻִҳFinishˡ


ļϴ
ڶļϴĿ163ֻһfileؼʵֶļϴ
ο163̵˼·˵˵ʵ֣
ȱһļռ䣨Լ֣е"idFile"ռ䲻ҪһdivͿԣҪfileؼFolderԾļռ
psҪǰfileؼļռʹǵfileؼ
˵˵FilesԣԷŵfileؼϣȡfileؼ桰ļбͻõ

ЩfileؼĳҪIniУ
Ǵļռеfileؼ

Code
this.Files = [];
//ļռ䣬ֵfileļ
Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){
    if(o.type == "file"){ o.value && this.Files.push(o); this.onIniFile(o); }
}))
ԿҪǰfileؼ뵽FilesУִиӺonIniFileģ

onIniFile: function(file){ file.value ? file.style.display = "none" : this.Folder.removeChild(file); }
ΪʵֵfileؼԭֵfileˣǸfileؼأ
𼱣žļռһµfileؼ

Code
var file = document.createElement("input");
file.name = this.FileName; file.type = "file"; file.onchange = Bind(this, function(){ this.Check(file); this.Ini(); });
this.Folder.appendChild(file);
ԿfileؼnameFileNameԵֵĬǿյģҪnameĻͿá
Կÿfileؼonchangeִм⺯Checkÿѡļ󶼻CheckһΣ˵˵Check

Code
//
var bCheck = true;
//пֵļ׺ֵͬ
if(!file.value){
    bCheck = false; this.onEmpty();
} else if(this.Limit && this.Files.length >= this.Limit){
    bCheck = false; this.onLimite();
} else if(!!this.ExtIn.length && !RegExp("\.(" + this.ExtIn.join("|") + ")$", "i").test(file.value)){
    //Ƿ׺
    bCheck = false; this.onNotExtIn();
} else if(!!this.ExtOut.length && RegExp("\.(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) {
    //Ƿֹ׺
    bCheck = false; this.onExtOut();
} else if(!!this.Distinct) {
    Each(this.Files, function(o){ if(o.value == file.value){ bCheck = false; } })
    if(!bCheck){ this.onSame(); }
}
һbCheckȻпֵļơ׺ͬļļ⣬һ費ͨbCheckͻΪfalseһõļṹ
˵˵׺js̨ȡļļֻܸͣݺ׺жϣжϣ

/\.(jpg|gif)$/i.test(file.value)
жȻǲģҪļжϵĻһҪں̨ContentTypeжһΡ
ûͨͻִonFail

!bCheck && this.onFail(file);
onFail趨Ƴûͨfileؼ

onFail: function(file){ this.Folder.removeChild(file); }

ͻʵ֣ȷ˵ģ⣩˵fileؼϴļЧˡ


ļб
IniУִһӺonIniûԼģҾļб

֮ǰ˵˵ļбĺAddListfileؼֵһtable档
Ĳһά飬еһάУtr,ڶάУtd
ȻȡбFileListٶһĵƬoFragmentdom

var FileList = $("idFileList"), oFragment = document.createDocumentFragment();
ȻEachѶά뵽ĵƬУ

Code
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);
})
һжif(typeof o == "string")ıֱinnerHTMLtdıﲻıһ󣩾appendChild뵽td
ݶ뵽ĵƬ׼ĵƬ뵽FileListУһFileListԭеݡ
innerHTMLΪFileListЧʣietableֻtd֧innerHTMLֻremoveChildգ

while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); }
֮Ϳ԰ĵƬˣ

FileList.appendChild(oFragment);

onIniֻҪҪʾһά飬AddListʾļбˣʱfileؼϵFilesԾʹôˡ
ȶһʾݵ飺

var arrRows = [];
ȻFiles鸳ֵ

Code
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;"]); }
AddRow(arrRows);
FilesûпؼʱֻûļпؼʱͻÿfileؼҪʾݷŵһУԿʵtdݵļϣŰ뵽arrRowsγɶά飬ѵõarrRowsAddRowʾݾˡ
ΪȡָfileؼһaɾDeleteҲһɣhrefΪ"javascript:void(0);"onclickзfalse̶ȵʵִֽjsȥת

ڱύʱҲҪʾļбύͲɾļˣֻʾļ·ˣ

Code
$("idBtnupload").onclick = function(){
    //ʾļб
    var arrRows = [];
    Each(fu.Files, function(o){ arrRows.push([o.value, "&nbsp;"]); });
    AddList(arrRows);
    
    fu.Folder.style.display = "none";
    $("idProcess").style.display = "";
    $("idMsg").innerHTML = "ļУԺ򡭡<br />пΪ⣬ֳʱӦ<a href='?'><font color='red'>ȡ</font></a>ϴļ";
    
    fu.Form.submit();
}
˵ύҪעһ⣬ǱǲǶ׵ģǰѱŵ֮⣬ûа취ʹ÷Ϊύڳ޸ύԣԾҪʹã

ļбˣȤĻҲԼװһܡ


fileʽ
ˣĹܶѾʵˣ163лһرĵطfileؼʽ
ù163ϴļ֪Ǹfileؼһťȷʵһfileؼ
Լ޸fileؼʽʱֵfileؼʽʵҪЧ
һ취һbuttonģ⣬ҲУjsfileؼӦǿǵȫɡ
ǲο163̺muxrwcģ126ӵЧܽ
1.ָһеidFile
ָߺͿoverflowΪhiddenǿ鼶ԪصdisplayΪblockΪ˸ߺͿȷ֣
2.һfileؼʽʹܴѡļĲָóȫ͸
ָ׼ȷĸߺͿΪͨfileؼвõʽ
3.Ѿģfileؼˣֱʽģfileؼʽˡ

ڳҪfileؼmargin-leftfont-sizeʵָ

Code
a.files input {
    margin-left:-350px;
    font-size:30px;
    cursor:pointer;
    filter:alpha(opacity=0);
    opacity:0;
}
ʹαhoveraԪأȻCSS2hoverӦκζ󣬵ie6֧֣
һõСɣһͼƬΪͨhoverʱ޸background-positionʵͼƬЧ

Code
a.files {
    width:90px;
    height:30px;
    overflow:hidden;
    display:block;
    border:1px solid #BEBEBE;
    background:url(img/fu_btn.gif) left top no-repeat;
    text-decoration:none;
}
a.files:hover {
    background-color:#FFFFEE;
    background-position:0 -30px;
}
ڵaʱһ߿Ȼ̫ۣ԰outlineΪnoneȥieֲ֧֣ҵһie԰hideFocusΪtrueؾ۽ʾ߿hideFocusjshtmlãҲͨexpressionŵcssУ

Code
a.files, a.files input {
    outline:none;/*ff* /
    hide-focus:expression(this.hideFocus=true);/*ie* /
}

ȫģ163̵Чˡ


̨

ǰ̨ˣ͵̨̨Ĺܼܺ򵥣Ǵݹļݡ
js + .Net ͼƬиϵͳʹashxļIHttpHandler͹ݡ
ܼ򵥣ֱˣ

Code
int iTotal = context.Request.Files.Count;

if (iTotal == 0)
{
    _msg = "û";
}
else
{
    int iCount = 0;

    for (int i = 0; i < iTotal; i++)
    {
        HttpPostedFile file = context.Request.Files[i];

        if (file.ContentLength > 0 || !string.IsNullOrEmpty(file.FileName))
        {
            //ļ
            file.SaveAs(System.Web.HttpContext.Current.Server.MapPath("./file/" + Path.GetFileName(file.FileName)));

            //Ըʵ
            if (++iCount > UploadFileLimit)
            {
                _msg = "ϴƣ" + UploadFileLimit;
                break;
            }
        }
    }
}
ֻļļƣļСȿԼչӦòѡ
֪֮ͨͻˣ

context.Response.Write("<script>window.parent.Finish('" + _msg + "');</script>");
iframeѾ˵ˡ


ʹ˵

ʹúܼ򵥣ʵһfileвֱformļռ

new FileUpload("uploadForm", "idFile")
ʵһ򵥵ˢϴļ

ʹ⼸ԣ
Form//
Folder//ļؼſռ
Files//ļ

ĹܿѡЩԣ
:Ĭֵ//˵
FileName:"",//ļϴؼnameϺ̨ʹ
FrameName:"",//iframenameҪԶiframeĻname
onIniFile:function(){},//ļʱִ(вfile)
onEmpty:function(){},//ļֵʱִ
Limit:0,//ļƣ0Ϊ
onLimite:function(){},//ļʱִ
Distinct:true,//Ƿͬļ
onSame:function(){},//ͬļʱִ
ExtIn:[],//׺
onNotExtIn:function(){},//׺ʱִ
ExtOut:[],//ֹ׺ExtInExtOutЧ
onExtOut:function(){},//ǽֹ׺ʱִ
onFail:function(){},//ļͨʱִ(вfile)
onIni:function(){}//ʱִ

ʹ÷Բοʵ

ṩ漸
Ini ռ
Check file
Delete ɾָfile
Clear ɾȫfile




ʽ

Code
.fu_list {
    width:600px;
    background:#ebebeb;
    font-size:12px;
}
.fu_list td {
    padding:5px;
    line-height:20px;
    background-color:#fff;
}
.fu_list table {
    width:100%;
    border:1px solid #ebebeb;
}
.fu_list thead td {
    background-color:#f4f4f4;
}
.fu_list b {
    font-size:14px;
}
/*fileʽ*/
a.files {
    width:90px;
    height:30px;
    overflow:hidden;
    display:block;
    border:1px solid #BEBEBE;
    background:url(img/fu_btn.gif) left top no-repeat;
    text-decoration:none;
}
a.files:hover {
    background-color:#FFFFEE;
    background-position:0 -30px;
}
/*fileΪ͸*/
a.files input {
    margin-left:-350px;
    font-size:30px;
    cursor:pointer;
    filter:alpha(opacity=0);
    opacity:0;
}
/*ȡʱ߿*/
a.files, a.files input {
    outline:none;/*ff*/
    hide-focus:expression(this.hideFocus=true);/*ie*/
}
html

Code
<form id="uploadForm" action="File.ashx">
  <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><a href="javascript:void(0);" class="files" id="idFile"></a> <img id="idProcess" style="display:none;" src="img/loading.gif" /></td>
      </tr>
      <tr>
        <td colspan="2"><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="2" style="color:gray">ܰʾͬʱϴ <b id="idLimit"></b> ļֻϴ <b id="idExt"></b> ļ </td>
      </tr>
      <tr>
        <td colspan="2" align="center" id="idMsg"><input type="button" value="ʼϴ" id="idBtnupload" disabled="disabled" />
          &nbsp;&nbsp;&nbsp;
          <input type="button" value="ȫȡ" id="idBtndel" disabled="disabled" />
        </td>
      </tr>
    </tbody>
  </table>
</form>



Code
var isIE = (document.all) ? true : false;

var $ = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Extend = function(destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }
}

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 FileUpload = Class.create();
FileUpload.prototype = {
  //ļؼſռ
  initialize: function(form, folder, options) {
    
    this.Form = $(form);//
    this.Folder = $(folder);//ļؼſռ
    this.Files = [];//ļ
    
    this.SetOptions(options);
    
    this.FileName = this.options.FileName;
    this._FrameName = this.options.FrameName;
    this.Limit = this.options.Limit;
    this.Distinct = !!this.options.Distinct;
    this.ExtIn = this.options.ExtIn;
    this.ExtOut = this.options.ExtOut;
    
    this.onIniFile = this.options.onIniFile;
    this.onEmpty = this.options.onEmpty;
    this.onNotExtIn = this.options.onNotExtIn;
    this.onExtOut = this.options.onExtOut;
    this.onLimite = this.options.onLimite;
    this.onSame = this.options.onSame;
    this.onFail = this.options.onFail;
    this.onIni = this.options.onIni;
    
    if(!this._FrameName){
        //Ϊÿʵͬiframe
        this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000);
        //ie޸iframename
        var oFrame = isIE ? document.createElement("<iframe name=\"" + this._FrameName + "\">") : document.createElement("iframe");
        //Ϊffname
        oFrame.name = this._FrameName;
        oFrame.style.display = "none";
        //ieĵδappendChildᱨ
        document.body.insertBefore(oFrame, document.body.childNodes[0]);
    }
    
    //formԣؼtargetҪָiframe
    this.Form.target = this._FrameName;
    this.Form.method = "post";
    //עieformûenctypeԣҪencoding
    this.Form.encoding = "multipart/form-data";

    //һ
    this.Ini();
  },
  //Ĭ
  SetOptions: function(options) {
    this.options = {//Ĭֵ
        FileName:    "",//ļϴؼnameϺ̨ʹ
        FrameName:    "",//iframenameҪԶiframeĻname
        onIniFile:    function(){},//ļʱִ(вfile)
        onEmpty:    function(){},//ļֵʱִ
        Limit:        0,//ļƣ0Ϊ
        onLimite:    function(){},//ļʱִ
        Distinct:    true,//Ƿͬļ
        onSame:        function(){},//ͬļʱִ
        ExtIn:        [],//׺
        onNotExtIn:    function(){},//׺ʱִ
        ExtOut:        [],//ֹ׺ExtInExtOutЧ
        onExtOut:    function(){},//ǽֹ׺ʱִ
        onFail:        function(){},//ļͨʱִ(вfile)
        onIni:        function(){}//ʱִ
    };
    Extend(this.options, options || {});
  },
  //ռ
  Ini: function() {
    //ļ
    this.Files = [];
    //ļռ䣬ֵfileļ
    Each(this.Folder.getElementsByTagName("input"), Bind(this, function(o){
        if(o.type == "file"){ o.value && this.Files.push(o); this.onIniFile(o); }
    }))
    //һµfile
    var file = document.createElement("input");
    file.name = this.FileName; file.type = "file"; file.onchange = Bind(this, function(){ this.Check(file); this.Ini(); });
    this.Folder.appendChild(file);
    //ִиӳ
    this.onIni();
  },
  //file
  Check: function(file) {
    //
    var bCheck = true;
    //ֵļơ׺ͬļ
    if(!file.value){
        bCheck = false; this.onEmpty();
    } else if(this.Limit && this.Files.length >= this.Limit){
        bCheck = false; this.onLimite();
    } else if(!!this.ExtIn.length && !RegExp("\.(" + this.ExtIn.join("|") + ")$", "i").test(file.value)){
        //Ƿ׺
        bCheck = false; this.onNotExtIn();
    } else if(!!this.ExtOut.length && RegExp("\.(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) {
        //Ƿֹ׺
        bCheck = false; this.onExtOut();
    } else if(!!this.Distinct) {
        Each(this.Files, function(o){ if(o.value == file.value){ bCheck = false; } })
        if(!bCheck){ this.onSame(); }
    }
    //ûͨ
    !bCheck && this.onFail(file);
  },
  //ɾָfile
  Delete: function(file) {
    //Ƴָfile
    this.Folder.removeChild(file); this.Ini();
  },
  //ɾȫfile
  Clear: function() {
    //ļռ
    Each(this.Files, Bind(this, function(o){ this.Folder.removeChild(o); })); this.Ini();
  }
}
Դ

Code
var fu = new FileUpload("uploadForm", "idFile", { Limit: 3, ExtIn: ["jpg", "gif"],
    onIniFile: function(file){ file.value ? file.style.display = "none" : this.Folder.removeChild(file); },
    onEmpty: function(){ alert("ѡһļ"); },
    onLimite: function(){ alert("ϴ"); },
    onSame: function(){ alert("Ѿͬļ"); },
    onNotExtIn:    function(){ alert("ֻϴ" + this.ExtIn.join("") + "ļ"); },
    onFail: function(file){ this.Folder.removeChild(file); },
    onIni: 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;"]); }
        AddList(arrRows);
        //ðť
        $("idBtnupload").disabled = $("idBtndel").disabled = this.Files.length <= 0;
    }
});

$("idBtnupload").onclick = function(){
    //ʾļб
    var arrRows = [];
    Each(fu.Files, function(o){ arrRows.push([o.value, "&nbsp;"]); });
    AddList(arrRows);
    
    fu.Folder.style.display = "none";
    $("idProcess").style.display = "";
    $("idMsg").innerHTML = "ļУԺ򡭡<br />пΪ⣬ֳʱӦ<a href='?'><font color='red'>ȡ</font></a>ϴļ";
    
    fu.Form.submit();
}

//ļбĺ
function AddList(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);
    })
    //ietable֧innerHTMLtable
    while(FileList.hasChildNodes()){ FileList.removeChild(FileList.firstChild); }
    FileList.appendChild(oFragment);
}


$("idLimit").innerHTML = fu.Limit;

$("idExt").innerHTML = fu.ExtIn.join("");

$("idBtndel").onclick = function(){ fu.Clear(); }

//ں̨ͨwindow.parentҳĺ
function Finish(msg){ alert(msg); location.href = location.href; }


asp汾䡿

ںܶasp汾ĺ̨дԾдһҡ
˻HTTPϴ2.1棨Ӧ°ˣϴ࣬õʱּ⣨֪Ҳûasp⣩
1fileؼnameǿʱ̨Ҳļ
2ļȽ϶ʱ"f"̨ҲҲļ
3жfileؼʹͬnamęֻᱣһļ
4ϴļ루ʱ

ǰ3ҼһRanNameԣΪtrueĻԶfileؼڵ4ҷֱдĵϾͲ룬ֱֶдĵûñֵ֪ôЩǵøŶ

