Asp.net C#:无法获取fileuploads的内部内容,因为内容不是文字

时间:2018-02-17 08:35:56

标签: c# asp.net

我正在使用asp.net c#开发一个Web应用程序。我正在尝试动态创建文件上传量。使用以下代码:

FileUpload[] fileuploadsarr = new FileUpload[uploads_table.Rows.Count];
int c = 0;

foreach (DataRow row in uploads_table.Rows)
{
    Label att_name = new Label();
    att_name.Text = row["TYPE"].ToString();
    FileUpload fileupload = new FileUpload();
    fileupload.CssClass = "form-control";
    fileupload.ID = "fileupload"+ row["ID"].ToString();
    fileupload.Attributes.Add("runat", "server");
    fileuploads.Controls.Add(att_name); 
    fileuploads.Controls.Add(fileupload);
    fileuploadsarr[c] = fileupload;
    c = c + 1;
 }

Session["myfileuploadsarr"] = fileuploadsarr;

当我尝试引用每个fileupload的postedfile时,我得到了空指针异常。当我调试代码时,我在文件上传的父属性中发现了这个异常

Parent = {InnerText = {System.Web.HttpException (0x80004005): Cannot get inner content of fileuploads because the contents are not literal.

注意:我在div

上添加了文件上传量
<div id="fileuploads" runat="server">

</div>

我通过以下方式引用filesupload:

FileUpload[] temp = (FileUpload[])Session["myfileuploadsarr"];          

foreach (FileUpload row in temp)
{
    OracleCommand cmd_docs = new OracleCommand();                  

    System.IO.Stream fs = row.PostedFile.InputStream;
    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
    ...
}

1 个答案:

答案 0 :(得分:1)

我认为你最好能使用ListView。它为您节省了生成动态控件的麻烦。请注意使用DataKeyNames

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
    <ItemTemplate>

        <asp:Label ID="Label1" runat="server" Text='<%# Eval("TYPE") %>'></asp:Label>
        <asp:FileUpload ID="FileUpload1" runat="server" CssClass="form-control"  />
        <br />

    </ItemTemplate>
</asp:ListView>

<asp:Button ID="Button1" runat="server" Text="Upload files" OnClick="Button1_Click" />

然后在代码后面将数据绑定到ListView并按下按钮处理上传的文件。

protected void Button1_Click(object sender, EventArgs e)
{
    //loop all items in the listview
    for (int i = 0; i < ListView1.Items.Count; i++)
    {
        //get the id from the datakeys if needed
        int ID = Convert.ToInt32(ListView1.DataKeys[i].Values[0]);

        //use findcontrol to locate the fileupload and cast it back
        FileUpload fu = ListView1.Items[i].FindControl("FileUpload1") as FileUpload;

        //check if it exists and has a file
        if (fu != null && fu.HasFile)
        {
            //save the file
        }
    }
}

将DataTable uploads_table绑定到ListView以完成此演示。

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack == false)
    {
        //bind the datatable to the listview
        ListView1.DataSource = uploads_table;
        ListView1.DataBind();
    }
}