0

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

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

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

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

4

1 回答 1

1

我认为你需要这样的东西

这篇文章展示了一个表结构(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();
    }
于 2013-06-15T23:50:21.433 回答