.net c# 提交包含文件file 的form表单 获得文件的Stream流

1.前台html代码  

    要写一个有id的form,可是不能有runat="server"属性。由于一个页面中,有这个属性的form表单仅仅能有一个。

再要有一个有name的iframe,要设置它的样式为不显示。即display为none。

使用iframe的优点是。提交该表单,

不会刷新页面,仅仅会刷新这个不可见的iframe。

    把form表单的target设置为iframe的name值,form表单的 action设置为表单要提交到的处理程序。

这个处理程序中。会接收到form表单中全部有name属性的控件的值,包括文件:

<input type="file" name="uploadfile" id="uploadfile" />

    WebForm的文件要想上传到server端,不能用.net本身的FileUpLoad控件,貌似是由于会遇到权限问题。无法解析。

所以,用本文所用的以表单的形式post过去,再在接收端用C#代码: 
var file = context.Request.Files[0]; var stream = file.InputStream;来获得文件和文件流。

 <form id="fileInfo" enctype="multipart/form-data" target="screct_frame" method="POST" action="../../Handlers/needsPlanCreateHandler.ashx?sign=readExcel">
    
     <input type="file" name="uploadfile" id="uploadfile" />
     <button class="btn btn-default" type="submit" >确定</button>                                        
                                       
 </form>
 <iframe name="screct_frame" style="display: none;"></iframe>
 
2.一般处理程序代码,即上面form所提交到的action端的处理代码
private void ReadExcel(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            try
            {
                var file = context.Request.Files[0];
                if (file.FileName == "")
                {
                    context.Response.Write("<script>parent.callback('请先导入文件');</script>");
                }
                var stream = file.InputStream;
                //这里能够对文件流做些什么
                
            }
            catch (Exception ex)
            {
                context.Response.Write("<script>parent.callback(" + ex.ToString() + ");</script>");
            }
        }
说明:上面的parent.callback()这种方法,callback()是iframe所在的页面定义的js方法,前面使用parent时由于。

当前提交的是在iframe中,使用parent能够获得页面对象,iframe能够通过parent或top来找到父级页面,

能够运行父级页面的js脚本。

原文地址:https://www.cnblogs.com/mfrbuaa/p/5182816.html