In this article I will explain with an example, how to upload and save (insert) file to Database Table, retrieve (display) files in HTML Grid and download the files from Database Table in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages (.Net Core 7), please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Database

This article makes use of a table named tblFiles whose schema is defined as follows.
ASP.Net Core Razor Pages: Upload Files, Save (Insert) file to Database and Download Files
 
Note: You can download the database table SQL by clicking the download link below.
           Download SQL file
 
 

Model

The Model class consists of following properties.
public class FileModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
}
 
 

Namespaces

You will need to import the following namespace.
using System.Data.SqlClient;
 
 

Razor PageModel (Code-Behind)

The PageModel consists of the following Handler methods.

Model Property

First, the public property of FileModel class names as Files is created as Generic List collection.
Then, the IConfiguration class is injected into the Constructor (IndexModel) with using Dependency Injection method.
Finally, the injected object is assigned to the Configuration property.
Note: For more details on Dependency Injection, please refer my article .Net Core 7: Dependency Injection in ASP.Net Core.
 

Handler method for handling GET operation

Inside this Handler method, the GetFiles method is called inside which the records from the tblFiles table are fetched using ExecuteReader and stored into a Generic List collection of FileModel class object.
Note: For more details on ExecuteReader method, please refer my article Using SqlCommand ExecuteReader Example in ASP.Net with C# and VB.Net.
 
Finally, the fetched records are assigned to the public property of Generic List collection of FileModel class.
 

Handler method for handling POST operation for uploading Files

This Handler method gets called, when a File is selected and the Upload Button is clicked.
This Handler method accepts the IFormFile as parameter.
Note: In case the IFormFile parameter is appearing NULL, please refer the article, ASP.Net Core: IFormFile always returns NULL.
 
The uploaded file is copied to MemoryStream class object and converted to BYTE Array and finally, is inserted into the database table along with File Name and Content Type.
After successful insertion of the File, RedirectToPage method is called which redirects to the IndexModel Get Handler method.
 

Handler method for handling File Download operation

When the Download Link inside the HTML Table (Grid) is clicked, then the ID of the particular file is sent to this Handler method and using the File ID, the File’s binary data is fetched from the database.
Finally, the File is downloaded using the File function which accepts the Binary data, Content Type and Name of the file.
public class IndexModel : PageModel
{
    public List<FileModel> Files { get; set; }
    private IConfiguration Configuration;
 
    public IndexModel(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public void OnGet()
    {
        this.Files = this.GetFiles();
    }
 
    public IActionResult OnPostUploadFile(IFormFile postedFile)
    {
        string fileName = Path.GetFileName(postedFile.FileName);
        string contentType = postedFile.ContentType;
        using (MemoryStream ms = new MemoryStream())
        {
            postedFile.CopyTo(ms);
            string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
            using (SqlConnection con = new SqlConnection(constr))
            {
                string sql = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)";
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    cmd.Parameters.AddWithValue("@Name", fileName);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Data", ms.ToArray());
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
 
        return RedirectToPage("Index");
    }
 
    public FileResult OnGetDownloadFile(int fileId)
    {
        byte[] bytes;
        string fileName, contentType;
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        string sql = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                cmd.Parameters.AddWithValue("@Id", fileId);
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["Data"];
                    contentType = sdr["ContentType"].ToString();
                    fileName = sdr["Name"].ToString();
                }
                con.Close();
            }
        }
 
        return File(bytes, contentType, fileName);
    }
 
    private List<FileModel> GetFiles()
    {
        List<FileModel> files = new List<FileModel>();
        string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
        string sql = "SELECT Id, Name FROM tblFiles";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        files.Add(new FileModel
                        {
                            Id = Convert.ToInt32(sdr["Id"]),
                            Name = sdr["Name"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }
        return files;
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The HTML Razor Page consists of an HTML Form.

Uploading the File

This Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation.
The Form consists of an HTML FileUpload and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostUploadFile but here it will be specified as UploadFile when calling from the Razor HTML Page.
 
When the Submit Button is clicked, the UploadFile Handler method for handling POST operation will be called.
 

Downloading the File

The HTML Table contains an HTML Anchor Link for downloading the File.
The URL of the Anchor Link is set using the @Url.Page method which accepts the following three parameters:
1. Name of the PageModel class.
2. Name of the Handler method.
3. The name and the value of the Parameters to be passed to the Handler method.
When any Download Link is clicked, the DownloadFile Handler method is called and the File is downloaded.
Note: In the Razor PageModel, the Handler method name is OnGetDownloadFile but here it will be specified as DownloadFile when calling from the Razor HTML Page.
 

Displaying the Files

For displaying the files, an HTML Table is used. A FOR EACH loop will be executed over the Model which will generate the HTML Table rows with the File records.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Upload_File_Database_Razor_Core.Pages.IndexModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="postedFile"/>
        <input type="submit" id="btnUpload" value="Upload" asp-page-handler="UploadFile" />
    </form>
    <hr />
    <table id="tblFiles" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:50px">File ID</th>
            <th style="width:120px">File Name</th>
            <th style="width:80px">Download</th>
        </tr>
        @foreach (var file in Model.Files)
        {
            <tr>
                <td>@file.Id</td>
                <td>@file.Name</td>
                <td><a href="@Url.Page("Index", "DownloadFile", new { fileId = file.Id })">Download</a></td>
            </tr>
        }
    </table>
</body>
</html>
 
 

Screenshot

ASP.Net Core Razor Pages: Upload Files, Save (Insert) file to Database and Download Files
 
 

Downloads