熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

ASP.NET2.0中將文件上傳到數據庫

2013-11-13 10:28:37  來源: .NET編程 

  此問題經常被人問本文列出將文字和圖片上傳到數據庫的方法包括Access數據庫和SQL Server數據庫

  Access數據庫代碼

  <%@ Page Language=C# EnableViewState=true %>

  <%@ Import Namespace=SystemDataOleDb %>
<!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>

  <script runat=server>

  protected void Button_Click( object sender EventArgs e )
  {
    SystemIOStream fileDataStream = FileUploadPostedFileInputStream;

  if (fileDataStreamLength < )
    {
      MsgText = 請選擇文件;
      return;
    }

  //得到文件大小
    int fileLength = FileUploadPostedFileContentLength;

  //創建數組
    byte[] fileData = new byte[fileLength];
    //把文件流填充到數組
    fileDataStreamRead(fileData fileLength);
    //得到文件類型
    string fileType = FileUploadPostedFileContentType;

  //構建數據庫連接SQL語句創建參數
    string strCnn = Provider=MicrosoftJetOLEDB;Data Source= + ServerMapPath(ImageAccessmdb);
    OleDbConnection myConnection = new OleDbConnection(strCnn);
    OleDbCommand command = new OleDbCommand(INSERT INTO Person (PersonNamePersonEmailPersonSexPersonImageTypePersonImage) +
    VALUES (@PersonName@PersonEmail@PersonSex@PersonImageType@PersonImage) myConnection);

  commandParametersAddWithValue(@PersonNameTextBoxText);
    commandParametersAddWithValue(@PersonEmail mengxia);
    commandParametersAddWithValue(@paramPersonSex );
    commandParametersAddWithValue(@PersonImageType fileType);
    commandParametersAddWithValue(@PersonImage fileData);

  //打開連接執行查詢
    myConnectionOpen();
    commandExecuteNonQuery();
    myConnectionClose();
    ResponseRedirect(RequestRawUrl);
  }

  protected void Page_Load( object sender EventArgs e )
  {

  if (!PageIsPostBack)
    {
      BindGrid();
    }
  }

  private void BindGrid( )
  {
    string strCnn = Provider=MicrosoftJetOLEDB;Data Source=
    + ServerMapPath(ImageAccessmdb);
    OleDbConnection myConnection = new OleDbConnection(strCnn);
    OleDbCommand myCommand = new OleDbCommand(SELECT * FROM Person myConnection);

  try
    {
      myConnectionOpen();
      GridViewDataSource = myCommandExecuteReader(SystemDataCommandBehaviorCloseConnection);
      GridViewDataBind();
    }
    catch (OleDbException SQLexc)
    {
      ResponseWrite(提取數據時出現錯誤 + SQLexcToString());
    }
  }
  protected string FormatURL( object strArgument )
  {
    return ReadImageaspx?id= + strArgumentToString();
  } 

  </script>

  <html xmlns=>
<head runat=server>
  <title>上傳文件到數據庫</title>
</head>
<body>
  <form id=MengXianhui runat=server>
    <asp:GridView ID=GridView runat=server AutoGenerateColumns=false>
      <Columns>
        <asp:TemplateField>
          <ItemTemplate>
            <%#Eval(PersonName) %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
          <ItemTemplate>
            <%#Eval(PersonEmail) %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
          <ItemTemplate>
            <%#Eval(PersonSex) %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
          <ItemTemplate>
            <img src=<%#FormatURL(Eval(PersonID)) %> /></ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
    <br />
    <br />
    姓名<asp:TextBox ID=TextBox runat=server></asp:TextBox>
    <br />
    照片<asp:FileUpload ID=FileUpload runat=server />
    <asp:Button ID=btnUpload runat=server Text=上傳 OnClick=Button_Click></asp:Button>
    <p>
      <asp:Label ID=Msg runat=server ForeColor=Red></asp:Label></p>
  </form>
</body>
</html>

   

  SQL Server數據庫代碼


  <%@ Page Language=C# EnableViewState=true %>

  <%@ Import Namespace=SystemDataSqlClient %>
<!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>

  <script runat=server>
  string strCnn = Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);;
  protected void Button_Click( object sender EventArgs e )
  {
    SystemIOStream fileDataStream = FileUploadPostedFileInputStream;

  if (fileDataStreamLength < )
    {
      MsgText = 請選擇文件;
      return;
    }

  //得到文件大小
    int fileLength = FileUploadPostedFileContentLength;

  //創建數組
    byte[] fileData = new byte[fileLength];
    //把文件流填充到數組
    fileDataStreamRead(fileData fileLength);
    //得到文件類型
    string fileType = FileUploadPostedFileContentType;

  //構建數據庫連接SQL語句創建參數

  SqlConnection myConnection = new SqlConnection(strCnn);
    SqlCommand command = new SqlCommand(INSERT INTO UserPhoto (UserNameContentTypePhoto) +
    VALUES (@UserName@ContentType@Photo) myConnection);

  commandParametersAddWithValue(@UserName TextBoxText);
    commandParametersAddWithValue(@ContentType fileType);
    commandParametersAddWithValue(@Photo fileData);

  //打開連接執行查詢
    myConnectionOpen();
    commandExecuteNonQuery();
    myConnectionClose();
    ResponseRedirect(RequestRawUrl);
  }

  protected void Page_Load( object sender EventArgs e )
  {

  if (!PageIsPostBack)
    {
      BindGrid();
    }
  }

  private void BindGrid( )
  {
    SqlConnection myConnection = new SqlConnection(strCnn);
    SqlCommand myCommand = new SqlCommand(SELECT * FROM UserPhoto Order By id DESC myConnection);

  try
    {
      myConnectionOpen();
      GridViewDataSource = myCommandExecuteReader(SystemDataCommandBehaviorCloseConnection);
      GridViewDataBind();
    }
    catch (Exception SQLexc)
    {
      ResponseWrite(提取數據時出現錯誤 + SQLexcToString());
    }
  }
  protected string FormatURL( object strArgument )
  {
    return ReadImageaspx?id= + strArgumentToString();
  } 

  </script>

  <html xmlns=>
<head id=Head runat=server>
  <title>上傳文件到數據庫</title>
</head>
<body>
  <form id=MengXianhui runat=server>
    <asp:GridView ID=GridView runat=server AutoGenerateColumns=false>
      <Columns>
        <asp:TemplateField>
          <ItemTemplate>
            <%#Eval(UserName) %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
          <ItemTemplate>
            <img src=<%#FormatURL(Eval(id)) %> /></ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
    <br />
    <br />
    姓名<asp:TextBox ID=TextBox runat=server></asp:TextBox>
    <br />
    照片<asp:FileUpload ID=FileUpload runat=server />
    <asp:Button ID=btnUpload runat=server Text=上傳 OnClick=Button_Click></asp:Button>
    <p>
      <asp:Label ID=Msg runat=server ForeColor=Red></asp:Label></p>
  </form>
</body>
</html>

  顯示圖片

  <%@ Page Language=C# %>

  <%@ Import Namespace=SystemDataOleDb %>
<%@ Import Namespace=SystemDataSqlClient %>
<script runat=server>

  protected void Page_Load( object sender EventArgs e )
  {
    ////構建數據庫連接SQL語句創建參數
    //ACCESS數據庫使用本注釋部分
    //string strCnn = Provider=MicrosoftJetOLEDB;Data Source= + ServerMapPath(ImageAccessmdb);
    //OleDbConnection myConnection = new OleDbConnection(strCnn);
    //OleDbCommand command = new OleDbCommand(select * from Person Where PersonID = + RequestQueryString[id] myConnection);
    //myConnectionOpen();
    //OleDbDataReader dr = commandExecuteReader();
    //if (drRead())
    //{
    //  ResponseClear();
    //  ResponseAddHeader(ContentType dr[PersonImageType]ToString());
    //  ResponseBinaryWrite((byte[])dr[PersonImage]);
    //}
    //drClose();
    //myConnectionDispose();

  //構建數據庫連接SQL語句創建參數
    string strCnn = Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);;
    SqlConnection myConnection = new SqlConnection(strCnn);
    SqlCommand command = new SqlCommand(select * from UserPhoto Where id = + RequestQueryString[id] myConnection);
    myConnectionOpen();
    SqlDataReader dr = commandExecuteReader();
    if (drRead())
    {
      ResponseClear();
      ResponseAddHeader(ContentType dr[ContentType]ToString());
      ResponseBinaryWrite((byte[])dr[Photo]);
    }
    drClose();
    myConnectionDispose();
  }
</script>

  創建SQL數據表語句

  CREATE TABLE [UserPhoto] (
 [id] [int] IDENTITY ( ) NOT NULL
 [UserName] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
 [ContentType] [varchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
 [Photo] [image] NOT NULL
 CONSTRAINT [PK_UserPhoto] PRIMARY KEY  CLUSTERED
 (
  [id]
 )  ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO


From:http://tw.wingwit.com/Article/program/net/201311/13767.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.