asp.net fileupload值到文本框

时间:2014-02-27 09:33:44

标签: c# asp.net file-upload

我正在使用formview将数据插入到我的数据库中。我必须使用文件upload.C​​ode来存储图像文件的名称。使用textbox。我只需要指导如何通过表单视图连接该文件上载。

代码:

<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlDataSource1" 
DefaultMode="Insert">

<InsertItemTemplate>
  Name:
    <asp:TextBox ID="shop_nameTextBox" runat="server" 
        Text='<%# Bind("shop_name") %>' />
    <br />
    shop_image:
    <asp:TextBox ID="shop_imageTextBox" runat="server" 
        Text='<%# Bind("shop_image") %>'  />
    <asp:FileUpload ID="FileUpload1" runat="server"  />
    <br />

    shop_desc:
    <asp:TextBox ID="shop_descTextBox" runat="server" 
        Text='<%# Bind("shop_desc") %>' />
    <br />


    shop_contact:
    <asp:TextBox ID="shop_contactTextBox" runat="server" 
        Text='<%# Bind("shop_contact") %>' />
    <br />
    <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
        CommandName="Insert" Text="Insert" />

    &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
        CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>

</asp:FormView>

我尝试将文本框连接到文件上传控件但是徒劳无功。谷歌搜索也没有得到回报。

1 个答案:

答案 0 :(得分:1)

如果我理解你的困境,以下应提供解决方案,taken from here

<form id="form1" runat="server">
    <asp:FileUpload id="FileUploadControl" runat="server" />
    <asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
    <br /><br />
    <asp:Label runat="server" id="StatusLabel" text="Upload status: " />
</form>

protected void UploadButton_Click(object sender, EventArgs e)
{
    if(FileUploadControl.HasFile)
    {
        try
        {
            if(FileUploadControl.PostedFile.ContentType == "image/jpeg")
            {
                if(FileUploadControl.PostedFile.ContentLength < 102400)
                {
                    string filename = Path.GetFileName(FileUploadControl.FileName);
                    FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
                    StatusLabel.Text = "Upload status: File " + FileUploadControl.FileName + " uploaded!";
                }
                else
                    StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
            }
            else
                StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

更新:是的,可以在inserttemplate中执行此操作,诀窍是使用FindControl方法,如下所示:

protected void BtnUpload_Click(object sender, EventArgs e)
{
    FormView formView = (FormView)((Button)sender).Parent.Parent;
    FileUpload fileUpload1 = (FileUpload)formView.FindControl("FileUpload1");

    if (fileUpload1.HasFile)
    {
        string filename = fileUpload1.FileName;
        //do inserting or uploading as you want
    }
}