Home > database >  How to Upload Files and Save in Database and download another page in ASP.NET Core MVC
How to Upload Files and Save in Database and download another page in ASP.NET Core MVC

Time:08-18

For download how to do the functionality in a form that we upload its store binary format how to retrieve data from binary file in the controller action

public IActionResult Index(IFormFile files)
{
        if (files != null)
        {
            if (files.Length > 0)
            {
                // Getting FileName
                var fileName = Path.GetFileName(files.FileName);

                // Getting file Extension
                var fileExtension = Path.GetExtension(fileName);

                // concatenating  FileName   FileExtension
                var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);

                var objfiles = new Files()
                {
                    DocumentId = 0,
                    Name= newFileName,
                    FileType = fileExtension,
                    CreatedOn = DateTime.Now
                };
                
                using (var target = new MemoryStream())
                {
                    files.CopyTo(target);
                    objfiles.DataFiles = target.ToArray();
                }

                _context.Files.Add(objfiles);
                _context.SaveChanges();
            }
        }

        return View();
}

CodePudding user response:

For download how to do the functionality in a form that we upload its store binary format how to retrieve data from binary file in the controller action

Do you mean you want to upload the file to the database, and then download the specified file from the database?

To upload file into the database, as you said, you need to use the IFormFile. Code like this:

public class Product
{
    [Key]
    public int ProId { get; set; }
    public string ProName { get; set; }
    public string ProImageName { get; set; }
    public byte[] ProImageContent { get; set; }
    public string ProImageContentType { get; set; }
    //you can add another properties
}

Upload method:

    [HttpPost]
    public async Task<IActionResult> CreateAsync(ProductViewModel product)
    {
        if (ModelState.IsValid)
        {
            //save image to database.
            using (var memoryStream = new MemoryStream())
            {
                await product.FormFile.CopyToAsync(memoryStream);

                // Upload the file if less than 2 MB
                if (memoryStream.Length < 2097152)
                {
                    //Convert the View 
                    var file = new Product()
                    {
                        ProImageName = product.FormFile.FileName,
                        ProImageContent = memoryStream.ToArray(),
                         
                        ProImageContentType = product.FormFile.ContentType,

                        ProName = product.Name
                    };
                    _dbcontext.Products.Add(file);

                    await _dbcontext.SaveChangesAsync();
                }
                else
                {
                    ModelState.AddModelError("File", "The file is too large.");
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View();
    }

Then, to download file, in the index list, you can add a hyperlink with the primary key, like this:

@Html.ActionLink("DownLoad Image", "DownloadImage", new {  id=item.ProId })

the whole index page code:

@model List<MVC6App.Data.Product>

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
} 
<p>
    <a asp-action="Create">Create New</a>
</p>

<table >
    <thead>
        <tr>
            <th>
                ProId
            </th>
            <th>
                ProName
            </th>
            <th>
                ProImageName
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null && Model.Count > 0)
        {
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProImageName)
                    </td>
                    <td>
                        @Html.ActionLink("DownLoad Image", "DownloadImage", new {  id=item.ProId })
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
        }
        else
        {
            <tr><td colspan="4"> empty</td></tr>
        }
    </tbody>
</table>

Controller Index action:

    public IActionResult Index()
    {
        var result = _dbcontext.Products.ToList();
        return View(result);
    }

And then, in the DownLoadImage action method, query the database based on the primary key and get the image/file content, after that return a File result to download the file:

    public IActionResult DownloadImage(int id)
    {
        byte[] bytes;
        string fileName, contentType;
        var item = _dbcontext.Products.FirstOrDefault(c => c.ProId == id);

        if(item != null)
        { 
            fileName = item.ProImageName;

            contentType = item.ProImageContentType;
            bytes = item.ProImageContent;
            return File(bytes, contentType, fileName);
        }
        return Ok("Can't find the Image");
    }

The result like this:

enter image description here

CodePudding user response:

  • Hello sir thank you so much I understand but when in download i need help enter code here ir because when I click download in it's going else condition

    Download :

    public IActionResult DownloadImage(int id) { byte[] bytes; string fileName, contentType; var item = _auc.Files.FirstOrDefault(c => c.DocumentId == id);

         if (item != null)
         {
             fileName = item.Name;
    
             contentType = item.FileType;
             bytes = item.DataFiles;
             return File(bytes, contentType, fileName);
         }
         return Ok("Can't find the File");
     }
    }
    

    on Controller for Create [upload document is okay I can see my files ) in database

    upload code in above enter image description here

  • Related