我看了别人用Iframe来实现网页的无刷新上传文件,但自己仿照写了一个却不行,请各位帮忙看一看,谢谢了。
客户端:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form name="form1" id="form1" action="index.ashx?cmd=ulf">
    <div>
        <input type="file" id="file" />
        <input type="button" id="upload" onclick="upload1()" value="上传" />
        <br />
        <div id="divBack" name="divBack">
    </form>
    <p>
        </p>
    <script type="text/javascript">
        function upload1() {
            var iframeFile = document.createElement("iframe");
            iframeFile.setAttribute("name", "file" + Math.floor(Math.random() * 1000));            document.body.appendChild(iframeFile);            this.form1.target = iframeFile.name;            this.form1.method = "post";            this.form1.enctype = "multipart/form-data";
            
            this.form1.action = "index.ashx?cmd=ulf";            
            this.form1.submit();        }        function Finish(msg) { window.alert(msg); location.href = location.href; }    </script>
</body>
</html>
服务器(文件名为index.ashx,用C#写的):
<%@ WebHandler Language="C#" Class="index" %>using System;
using System.Web;
using System.Collections.Generic;
public class index : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        
        string ms = "";
        int count = context.Request.QueryString.Count;
        string cmd="";
        for(int i=0;i<count;i++)
        {
            cmd=context.Request.QueryString[i];
            if("ulf"==cmd)
            {
                ms+=upLoadFile(context);
                break;
            }
        }
        context.Response.ContentType = "text/html";
        context.Response.Write("<script>window.parent.Finish('"+ms+"')</script>");
             }    private string upLoadFile(HttpContext context) {
        int fc = context.Request.Files.Count;
        string ms = "";
        HttpPostedFile file;
        System.Web.Configuration.HttpRuntimeSection hs = new System.Web.Configuration.HttpRuntimeSection();
        int fl=hs.MaxRequestLength*1024;
        for (int i = 0; i < fc; i++)
        {
            file=context.Request.Files[i];
            if(file.ContentLength>fl)
            {
                break;
                ms+="文件“"+file.FileName+"“超出上传允许大小!</br>";
            }
            
            
            file.SaveAs(context.Server.MapPath("files")+"\\"+file.FileName);
            
            ms+="文件“"+file.FileName+"“上传成功!</br>";
            
        }
        if (ms == "")
        {
            ms = "没有上传的文件"; 
        }        return ms;
        
    }
    public bool IsReusable
    {
        get {
            return false;
        }
    }}