FileUpload HashFile返回结果总是false,解决方案

转自:http://www.codeproject.com/Articles/26297/FileUpload-with-Master-Page-Ajax-Update-Panel-Form


Introduction

It’s my first article for ASP.NET. Generally I write code in the network field with C#.NET but since a few days, I was working in Web development and facing various problems. I'm writing this article after finding a solution to a problem that I faced in my project. You can see my blog here.

Background

A few days ago, I was trying to make a file upload module in my project. It is an Ajax based project with Master-Content page. I was using Form View control to insert-update & show data, and for ADO.NET using Object Data Source. The problem was as follows:

  1. Ajax does not support File upload control (because file upload control needs complete post back event), and Ajax code is in the Master page, but file upload control is in the content page within form view.
  2. Form view control uses object data source to insert data, here I can't bind with file upload control with object data source because in file upload control does not have property to bind.

To solve it, I posted my question in the ASP.NET forum and also searched a lot, but I did not find any solution.

Using the Code

To solve my first problem, I've taken the help of others from the ASP.NET site. To upload a file in Ajax, it needs to register as post back control. And to register it, just write code as shown below:

ScriptManager.GetCurrent(this).RegisterPostBackControl(Control Id);    

But the problem is in the second point. How can we bind Object Data Source property with File upload control. I've not got any property to bind. So I've do it in another way. In page load event has assigned file upload control’s file name with a text box and that text box has binded with object data source. Here all controls like file upload control, button, text box are in form view control. So I've written code like:

if (Page.IsPostBack)
        {
            if (FormView1.CurrentMode == FormViewMode.Insert)
            {
                FileUpload objFU = (FileUpload)FormView1.FindControl("FileUpload1");
                TextBox objTB = (TextBox)FormView1.FindControl("TextBox1");
                if (objFU.HasFile)
                {
                    objTB.Text = objFU.FileName;
                    objFU.SaveAs(Server.MapPath(".") + "/" + objFU.FileName);
                }
            }
        }

Now the problem has been solved.

In that solution, I'm not describing about how you can access database in SQL Server. You just need to create a table with that SQL script:

CREATE TABLE [testFile]([fileName] [varchar](50) ,[other] [nchar](10))         

Here it also has one section to see that Ajax facility has put get server time. So the entire code is in ASP.NET for the Master page:

<%@ Master Language="C#" AutoEventWireup="true" 
	CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
	Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" ></asp:ScriptManager>
        <asp:UpdatePanel ID="upPnl" runat="server">
        <ContentTemplate>
    <div>
    
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>        

And for content page:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" 
	AutoEventWireup="true" CodeFile="Default.aspx.cs" 
	Inherits="Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        
        <div style="border:Solid 1px; width:350px; text-align:center; 
			padding:10px 5px 10px 5 px; ">
        Non Ajax Area For File Upload
            <asp:FormView ID="FormView1" runat="server" 
		DataSourceID="ObjectDataSource1" DefaultMode="Insert">
                <InsertItemTemplate>
                    <asp:FileUpload ID="FileUpload1" runat="server"  />
                    <asp:Button ID="Button1" runat="server" 
			CommandName="Insert" Text="Save" />
                    <br />
                    <asp:TextBox ID="TextBox1" Visible="false" 
			runat="server" Text='<%# Bind("FileName") %>'></asp:TextBox>
                    <br />
                    Other Text: <asp:TextBox ID="TextBox2" 
			runat="server" Text='<%# Bind("Other") %>'></asp:TextBox>
                </InsertItemTemplate>
            </asp:FormView>
            <asp:ObjectDataSource ID="ObjectDataSource1" 
			runat="server" InsertMethod="Insert"
                SelectMethod="Select" TypeName="BL" DataObjectTypeName="BL">
            </asp:ObjectDataSource>
        </div>
        
        <br />
        <div style="border:solid 1px; width:350px; 
			text-align:center;padding:10px 5px 10px 5 px; ">
        Ajax Area To Get Server Time
        <br />
        <asp:Button ID="Button2" runat="server" 
		Text="Get Server Time" OnClick="Button2_Click" /><br />
        Server Time Is: 
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>     
   
</asp:Content>       

And in business logic, the code is:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DbClass;
/// <summary>
/// Summary description for BL
/// </summary>
public class BL
{
    DbClass.SqlDbAccess objDB = new SqlDbAccess
				(ConfigurationManager.AppSettings["ConnStr"]);
    public BL()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    private string _fileName;
    private string _other;
    public string FileName
    {
        get { return _fileName; }
        set { _fileName = value; }
    }

    public string Other
    {
        get { return _other; }
        set { _other = value; }
    }

    public void Insert(BL objectBl)
    {
        objDB.ExecuteNonQuery("INSERT INTO 
		[test].[dbo].[testFile]([FileName],[Other])VALUES
		('"+objectBl.FileName+"','"+objectBl.Other+"')");

    }
    public DataTable  Select()
    {
        return objDB.GetDataTable("SELECT FileName,Other FROM [test].[dbo].[testFile]");
    }
}

In code behind of content page:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.GetCurrent(this).RegisterPostBackControl(FormView1); //可以解决问题

        if (Page.IsPostBack)
        {
            if (FormView1.CurrentMode == FormViewMode.Insert)
            {
                FileUpload objFU = (FileUpload)FormView1.FindControl("FileUpload1");
                TextBox objTB = (TextBox)FormView1.FindControl("TextBox1");
                if (objFU.HasFile)
                {
                    objTB.Text = objFU.FileName;
                    objFU.SaveAs(Server.MapPath(".") + "/" + objFU.FileName);
                }
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }
}       

The entire project has been attached with this article, please take a look at it for more details.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值