簡體   English   中英

上傳下載文件Visual Studio

[英]Upload Download File Visual Studio

我已經使用Visual Studio C#創建了一個網站,為學生和老師提供了不同的功能。 剩下的唯一一件事是,我希望再創建兩個頁面,一個在教師文件夾中,另一個在學生文件夾中(訪問取決於角色)。

教師端頁面將文件(任何格式)上傳到數據庫。 我相信這將以varbinary形式存儲在表中。 並且學生側的頁面提供了下載所需文件的鏈接。 我現在瀏覽了許多不同的網頁,但是似乎無法實現任何解決方案。 請有人能告訴我該怎么做嗎?

我相信上傳更容易。 我需要做的就是實現FileUpload控件,並使用查詢可以將數據存儲在表中。

但是下載呢? 我看到了一個使用HttpHandlers的示例,但這是在瀏覽器中顯示圖像的示例。 我想上傳其他格式的文件,然后將其下載到計算機上(也就是說,學生可以下載它)

我認為你需要像這樣

本文顯示了一種表結構(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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM