上传下载文件Visual Studio

时间:2013-06-15 23:43:04

标签: c# asp.net visual-studio-2010 file-upload download

我使用Visual Studio C#创建了一个网站,为学生和教师提供不同的功能。唯一剩下的就是我希望再创建两个页面,一个在教师文件夹中,另一个在学生文件夹上(访问权限取决于角色)。

教师方面的页面将文件(以任何格式)上传到数据库。我相信这将以varbinary的形式存储在表中。学生端的页面提供了下载所需文件的链接。我现在经历了很多不同的网页,但似乎无法实现任何解决方案。请有人能告诉我怎么做吗?

我相信上传更容易。我需要做的就是实现FileUpload控件并使用查询我可以将数据存储在表中。

但下载呢?我看到了一个使用HttpHandlers的例子,但那是用于在浏览器中显示图像。我想上传其他格式的文件,然后在电脑上下载(即学生可以下载)

1 个答案:

答案 0 :(得分:1)

我认为你需要像this这样的东西。

本文展示了一个用于存储任何类型二进制文件的表结构(SQL Server):

CREATE TABLE [dbo].[Files](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [ContentType] [varchar](50) NOT NULL,
    [Size] [bigint] NOT NULL,
    [Data] [varbinary](max) NOT NULL,
    CONSTRAINT [PK_Files] PRIMARY KEY CLUSTERED 
    (
    [ID] ASC
    )WITH (
        PAD_INDEX  = OFF,
        STATISTICS_NORECOMPUTE  = OFF, 
        IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS  = ON,
        ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

在您的上传页面中,添加以下控件:

<input type="file" name="fileInput" />
<asp:Button ID="btnUpload" Text="Upload File" runat="server" onclick="btnUpload_Click" />

转到上传页面的代码隐藏文件,并添加以下代码以处理按钮的单击事件并将文件保存到数据库:

protected void btnUpload_Click(object sender, EventArgs e)
{
    HttpFileCollection files = Request.Files;
    foreach (string fileTagName in files)
    {
            HttpPostedFile file = Request.Files[fileTagName];
            if (file.ContentLength > 0)
            {
                    int size = file.ContentLength;
                    string name = file.FileName;
                    int position = name.LastIndexOf("\\");
                    name = name.Substring(position + 1);
                    string contentType = file.ContentType;
                    byte[] fileData = new byte[size];
                    file.InputStream.Read(fileData, 0, size);

                    FileUtilities.SaveFile(name, contentType, size, fileData);
            }
    }
    DataTable fileList = FileUtilities.GetFileList();
    gvFiles.DataSource = fileList;
    gvFiles.DataBind();
}

FileUtilities类必须具有保存文件的方法,然后才能从数据库中检索它:

public static void SaveFile(string name, string contentType, int size, byte[] data)
{
    using (SqlConnection connection = new SqlConnection())
    {
        OpenConnection(connection);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = connection;
        cmd.CommandTimeout = 0;

        string commandText = "INSERT INTO Files VALUES(@Name, @ContentType, ";
        commandText = commandText + "@Size, @Data)";
        cmd.CommandText = commandText;
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100);
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50);
        cmd.Parameters.Add("@size", SqlDbType.Int);
        cmd.Parameters.Add("@Data", SqlDbType.VarBinary);

        cmd.Parameters["@Name"].Value = name;
        cmd.Parameters["@ContentType"].Value = contentType;
        cmd.Parameters["@size"].Value = size;
        cmd.Parameters["@Data"].Value = data;
        cmd.ExecuteNonQuery();

        connection.Close();
    }
}

public static DataTable GetFileList()
{
        DataTable fileList = new DataTable();
        using (SqlConnection connection = new SqlConnection())
        {
            OpenConnection(connection);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandTimeout = 0;

            cmd.CommandText = "SELECT ID, Name, ContentType, Size FROM Files";
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter();

            adapter.SelectCommand = cmd;
            adapter.Fill(fileList);

            connection.Close();
        }

        return fileList;
}

public static DataTable GetAFile(int id)
{
        DataTable file = new DataTable();
        using (SqlConnection connection = new SqlConnection())
        {
            OpenConnection(connection);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;
            cmd.CommandTimeout = 0;

            cmd.CommandText = "SELECT ID, Name, ContentType, Size, Data FROM Files "
                + "WHERE ID=@ID";
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter();

            cmd.Parameters.Add("@ID", SqlDbType.Int);
            cmd.Parameters["@ID"].Value = id;

            adapter.SelectCommand = cmd;
            adapter.Fill(file);

            connection.Close();
        }

        return file;
}

要列出可用文件,请在下载页面添加GridView

<asp:GridView ID="gvFiles" CssClass="GridViewStyle"
            AutoGenerateColumns="true" runat="server">
            <FooterStyle CssClass="GridViewFooterStyle" />
            <RowStyle CssClass="GridViewRowStyle" />    
            <SelectedRowStyle CssClass="GridViewSelectedRowStyle" />
            <PagerStyle CssClass="GridViewPagerStyle" />
            <AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
            <HeaderStyle CssClass="GridViewHeaderStyle" />
            <Columns>
                    <asp:TemplateField>
                            <ItemTemplate>
                                    <asp:HyperLink runat="server"
                                            NavigateUrl='<%# Eval("ID", "GetFile.aspx?ID={0}") %>'
                                            Text="Download"></asp:HyperLink>
                            </ItemTemplate>
                    </asp:TemplateField>
            </Columns>
    </asp:GridView>

并通过添加以下代码隐藏来加载它:

protected void Page_Load(object sender, EventArgs e)
{
        if (! IsPostBack)
        {
            DataTable fileList = FileUtilities.GetFileList();
            gvFiles.DataSource = fileList;
            gvFiles.DataBind();
        }
}

最后,在GetFile页面中,将以下内容添加到代码隐藏中以实现下载功能:

protected void Page_Load(object sender, EventArgs e)
    {
        int id = Convert.ToInt16(Request.QueryString["ID"]);

        DataTable file = FileUtilities.GetAFile(id);
        DataRow row = file.Rows[0];

        string name = (string)row["Name"];
        string contentType = (string)row["ContentType"];
        Byte[] data = (Byte[])row["Data"];

        // Send the file to the browser
        Response.AddHeader("Content-type", contentType);
        Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
        Response.BinaryWrite(data);
        Response.Flush();
        Response.End();
    }