无upload组件上传文件

来源:互联网 发布:淘宝全球购入口 编辑:程序博客网 时间:2024/03/29 07:36

这里有一个办法,如果是ie6则要首先在ie”安全“中启用“ 执行activex”

 

如果是ie7及以后版本,无需设置。

 

 

原理:既然ie不允许我们用js设置file组件的value值,必须要手动选择路径,那么我们可以模拟键盘输入欺骗ie。

<script>
 WshShell=new ActiveXObject("WScript.Shell"); //首先ie要允许执行activex
function ss()

var obj=document.getElementById("File1");
obj.focus();//定位焦点到file
obj.value="";
WshShell.sendKeys("C:/1.txt");//采用模拟按键来设置要上传的客户端文件路径
setTimeout('document.getElementById("Button1").click();',100);//这里必须有个延迟,不能太短,否则obj.focus();这句来不及执行
}  
 </script>

 

页面body代码:
<body>
    <form id="form1" runat="server">
   <div>
       <input id="File1" type="file" name="sz" runat="server"  style="width:0px; height:0px; border:0;"/>
       <input id="Button2" type="button" value="button" onclick="ss()" />
       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" Width=0 /></div>
    </form>
</body>

 

 

cs代码:
protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(test1());
    }

    protected string test1()
    {
        HttpFileCollection files = HttpContext.Current.Request.Files;//获取客户端file
        int a = files.Count;//在我们这里count为1
        string ss = files[0].FileName;//下断点可以看到已经获取到客户端路径
        files[0].SaveAs("C://2.txt");//保存到服务端路径C://下
        return ss;
    }

虽然可以成功,不过个人认为这个方法不好。

原创粉丝点击