Asp.net 中文件的上传和下载

来源:互联网 发布:淘宝网雪纺胖妹妹长袖 编辑:程序博客网 时间:2024/04/27 23:39


前台- File_upload.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="File_Upload.aspx.cs" Inherits="File_Upload" %>

 

<!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>多文件上传</title>

    <script language="JavaScript">

    function addFile()

    {

    var str = '<INPUT type="file" size="50" NAME="File">'

    document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)

    }

    </script>

</head>

 

<body>

    <form id="form2" method="post" runat="server" enctype="multipart/form-data">

      <div align="center">

        <h3>多文件上传</h3>

        <P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>

        <P>

          <input type="button" value="增加(Add)" onclick="addFile()">

          <input onclick="this.form.reset()" type="button" value="重置(ReSet)">

          <asp:Button Runat="server" Text="开始上传" ID="Button1" OnClick="UploadButton_Click"></asp:Button>

        </P>

        <P>

        <asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"

          Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>

        </P>

       

         <br />

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="335px" OnRowCommand="Gridview_RowCommand">

            <Columns>

                <asp:BoundField DataField="ID" HeaderText="ID" />

                <asp:BoundField DataField="Name" />

                <asp:ButtonField ButtonType="Image" CommandName="Download" HeaderText="Download" ImageUrl="~/images/mailto.gif"

                    Text="Download" />

            </Columns>

        </asp:GridView>

      </div>

    </form>

</body>

</HTML>

 

 

后台:File_Upload.aspx.cs

 

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;

using System.IO;

using System.Data.Sql;

using System.Data.SqlClient;

 

 

public partial class File_Upload : System.Web.UI.Page

{

    private string connString;

   

    private void InitalDB()

    {

        string uid = System.Configuration.ConfigurationManager.AppSettings.Get("uid");

        string pwd = System.Configuration.ConfigurationManager.AppSettings.Get("pwd");

        string server = System.Configuration.ConfigurationManager.AppSettings.Get("server");

        string database = System.Configuration.ConfigurationManager.AppSettings.Get("database");

        connString = "Server=" + server + ";uid=" + uid + ";pwd=" + pwd + ";database=" + database;

 

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

        InitalDB();

        BindData();

    }

    protected void UploadButton_Click(object sender, EventArgs e)

    {

        ///'遍历File表单元素

        HttpFileCollection files = HttpContext.Current.Request.Files;

 

        /// '状态信息

        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        strMsg.Append("上传的文件分别是:<hr color=red>");

        try

        {

            for (int iFile = 0; iFile < files.Count; iFile++)

            {

                ///'检查文件扩展名字

                HttpPostedFile postedFile = files[iFile];

                string fileName, fileExtension;

                fileName = System.IO.Path.GetFileName(postedFile.FileName);

                if (fileName != "")

                {

                    fileExtension = System.IO.Path.GetExtension(fileName);

                    strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");

                    strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");

                    strMsg.Append("上传文件的文件名:" + fileName + "<br>");

                    strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");

                    ///'可根据扩展名字的不同保存到不同的文件夹

                    ///注意:可能要修改你的文件夹的匿名写入权限。

                    ///

 

                    FileStream fs = new FileStream(postedFile.FileName, FileMode.Open, FileAccess.Read);

                    BinaryReader br = new BinaryReader(fs);

                    byte[] bytes = br.ReadBytes((int)fs.Length);

                    br.Close();

                    fs.Close();

 

                    SqlConnection myConn = new SqlConnection(connString);

                    string strComm = "insert into tb_files(name,File_Data,File_Size)values('" + fileName + "',@FileBinary, '" + fileName.Length + "')";

                    SqlCommand myComm = new SqlCommand(strComm, myConn);

                    myComm.Parameters.Add("@FileBinary", SqlDbType.Image);

                    myComm.Parameters["@FileBinary"].Value = bytes;

                    myConn.Open();

                    myComm.ExecuteNonQuery();

                    myConn.Close();

 

                    //postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);

 

                }

            }

            strStatus.Text = strMsg.ToString();

        }

        catch (System.Exception Ex)

        {

            strStatus.Text = Ex.Message;

        }

    }

 

 

    private void BindData()

    {

        DataTable dt = new DataTable();

        SqlConnection myConn = new SqlConnection(connString);

        string sql = "select id,name,File_Size from tb_files ";

        myConn.Open();

        SqlDataAdapter adp=new SqlDataAdapter(sql,myConn);

        adp.Fill(dt);

        GridView1.DataSource = dt;

        GridView1.DataBind();

  

    }

 

 

 

    protected void Gridview_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Download")

        {

            DataTable dt = new DataTable();

            SqlConnection myConn = new SqlConnection(connString);

            string sql = "select id,name,File_Size,file_data from tb_files where id='9' ";

            myConn.Open();

            SqlDataAdapter adp = new SqlDataAdapter(sql, myConn);

            adp.Fill(dt);

            if (dt.Rows.Count > 0)

            {

                Response.Buffer = true;

                Response.Clear();

                Response.ContentType = "application/x-msexcel";

                Response.BinaryWrite((byte[])dt.Rows[0]["file_data"]);    

                }

 

        }

    }

}

原创粉丝点击