简体   繁体   English

上传下载文件Visual Studio

[英]Upload Download File Visual Studio

I have created a website using Visual Studio C#, with different functionalities for students and teachers. 我已经使用Visual Studio C#创建了一个网站,为学生和老师提供了不同的功能。 The only thing remaining is that I wish to create two more pages, one in the teacher folder, and other on the student folder (access is dependant on roles). 剩下的唯一一件事是,我希望再创建两个页面,一个在教师文件夹中,另一个在学生文件夹中(访问取决于角色)。

The page on the teacher side uploads a file (in any format) to a database. 教师端页面将文件(任何格式)上传到数据库。 This I believe will be stored in a table in the form of varbinary. 我相信这将以varbinary形式存储在表中。 And the page on student side provides a link to download the desired file. 并且学生侧的页面提供了下载所需文件的链接。 I have been through a lot of different web pages now, but can't seem to achieve any solution to it. 我现在浏览了许多不同的网页,但是似乎无法实现任何解决方案。 Please can someone tell me how to do it?? 请有人能告诉我该怎么做吗?

I believe that uploading is easier. 我相信上传更容易。 All I need to do is implement a FileUpload control and using a query I can store that the data in a table. 我需要做的就是实现FileUpload控件,并使用查询可以将数据存储在表中。

But what about downloading? 但是下载呢? I saw an example which used HttpHandlers, but that was for displaying images in the browser. 我看到了一个使用HttpHandlers的示例,但这是在浏览器中显示图像的示例。 I want to upload files in other format and then download the same on the computer (that is the student would be able to download it) 我想上传其他格式的文件,然后将其下载到计算机上(也就是说,学生可以下载它)

I think you need something like this . 我认为你需要像这样

The article shows a table structure (SQL Server) to store any kind of binary file: 本文显示了一种表结构(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]

In your upload page, put the following controls: 在您的上传页面中,放置以下控件:

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

Go to the code-behind file of you upload page and add the following code to handle the button's click event and save the file to the database: 转到您上载的代码隐藏文件页面,并添加以下代码来处理按钮的单击事件并将该文件保存到数据库:

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();
}

The FileUtilities class must have methods to save the file and later retrieve it from the database: 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;
}

To list the available files add a GridView to you download page: 要列出可用文件,请向您的下载页面添加一个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>

and load it by adding the following code-behind: 并通过添加以下代码来加载它:

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

Finally, in the GetFile page add the following to the code-behind in order to implement the download feature: 最后,在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.

相关问题 Visual Studio Lightswitch上传和下载文件 - Visual studio lightswitch upload and download files 在 mvc 中上传文件时,Visual Studio 调试会立即停止吗? - Visual Studio debugging stop immediately on file upload in mvc? 在Visual Studio Web表单中使用通用处理程序拖放上传文件 - Drag and Drop upload file by using Generic Handler in visual studio webform Visual Studio Web,我要上传什么文件到服务器? - Visual studio web, what file do i upload to server? Visual Studio没有响应上传大小为6MB的文件 - Visual studio is not responding to upload a file of size 6MB 文件上传在 Visual Studio IIS Express 中工作但不在服务器上 - File upload working in Visual Studio IIS Express but not on server 在Visual WebGUI中上传文件 - File upload in Visual WebGUI 如何使用Selenium C#从webapp下载生成的pdf文件并将其附加到Visual Studio中的测试结果 - How to download generated pdf file from webapp and attach it to test results in Visual Studio using Selenium C# Visual Studio 2010 ASP.net c# 在运行时下载超链接文件不起作用 - Visual Studio 2010 ASP.net c# Download file for hyper link at runtime not working 我可以制作 Visual Studio 解决方案文件来自动下载 NuGet 包吗? - Can I make a Visual Studio solution file to automatically download a NuGet package?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM