11/20/2018

ASP.NET how to upload file to a server using class HttpPostedFileBase

Here I want to tell you about uploading a file to a server and storing it in a database.





























First we must create a local database file in the project.
















We also make a button to select the file on the disk.
Then we need to define the function Create() that writes the file to the database.
For this we will use a class HttpPostedFileBase.
Also add the ability to upload a file from the server using the function DownLoadFile().
Another function DeleteFile() will be responsible for deleting the file on the server.

All program code:


public class File
{
 public int Id { get; set; }
 public string FileName { get; set; }
 public string ContentType { get; set; }          
 public byte[] Content { get; set; }
}

public class HomeController : Controller
{
 DbUplFileContext db = new DbUplFileContext();

 public ActionResult Index()
 {
  return View(db.Files);
 }
  
 [HttpPost]
 public ActionResult Create(File model, HttpPostedFileBase someFile)
 {
  var f_file = new File();
  f_file.FileName = System.IO.Path.GetFileName(someFile.FileName);
  f_file.ContentType = someFile.ContentType;

  using (var reader = new System.IO.BinaryReader(someFile.InputStream))
  {
   f_file.Content = reader.ReadBytes(someFile.ContentLength);
  }

  db.Files.Add(f_file);
  db.SaveChanges();

  return RedirectToAction("Index", "Home");
 }

 public ActionResult DownLoadFile(int id)
 {
  File fileToRetrieve = db.Files.Find(id);
  return File(fileToRetrieve.Content, fileToRetrieve.ContentType, fileToRetrieve.FileName);
 }

 public ActionResult DeleteFile(int id)
 {
  File fileToDelete = db.Files.Find(id);
  if (fileToDelete != null)
  {
   db.Files.Remove(fileToDelete);
   db.SaveChanges();
  }
  return RedirectToAction("Index", "Home");
 }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@model IEnumerable<File_upload.Models.File>

@{
    ViewBag.Title = "Home Page";
}
<br />
<br />

<style>
    table {
        border-spacing: 6px;
        border-collapse: separate;
    }

    td, th {
        border: solid 1px #ccc;
    }
</style>

<table>
    <tr>
        <td><p><h3>File name</h3></p></td>
    </tr>
    @foreach (File_upload.Models.File b in Model)
    {
        <tr>
            <td> <p>@b.FileName</p></td>
            <td> <p> <a href='@Url.Action("DownLoadFile", "Home", new { id = b.Id }, null)'>Download</a></p> </td>
            <td> <p> <a href='@Url.Action("DeleteFile", "Home", new { id = b.Id }, null)'>Delete</a></p> </td>
        </tr>
    }
</table>

<br />
<br />
<br />
<p><h3>Add File</h3></p>

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="someFile" />
    <br />
    <input type="submit" value="Upload" name="UploadButton" id="UploadButton" />
}