Home > Back-end >  Download the attachment from the controller ASP.NET MVC
Download the attachment from the controller ASP.NET MVC

Time:11-01

This is my code to retrieve the image from the database and show it to the user.

Then It will open on another blank tab and view.

Now I want to know, rather than viewing the attachment on another tab, I want to download the file from the controller.

How to download the file?

Here is my code in HTML

 @Html.ActionLink(item.File_Name, "PaymentAttachmentView", "TaskMains", new { id = item.Id }, new { @target = "_blank" })

This is my code in the controller

public ActionResult RetrieveTaskImage(int id)
        {

            var q = from c in db.TaskFiles where c.Id == id select c.Attachment;
            var type = from t in db.TaskFiles where t.Id == id select t.File_Name;
            string fileType = type.First().ToString();
            string ext = Path.GetExtension(fileType);
            byte[] cover = q.First();
            if (cover != null)
            {
                if (ext == ".pdf")
                {
                    return File(cover, "application/pdf");
                }
                else
                {
                    return File(cover, "image/jpg");
                }

            }
            else
            {
                return null;
            }


        }

CodePudding user response:

You could try in following way:

Way: 1

Controller:

public async Task<IActionResult> DownloadImage(string imageName)
        {
            var path = Path.GetFullPath("./wwwroot/ImageName/Cover/"   imageName);
            MemoryStream memory = new MemoryStream();
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, "image/png", Path.GetFileName(path));
        }

Download Link HTML:

<a asp-controller="Application"  asp-action="DownloadImage"  asp-route-imageName="@item.ImageName">Download</a>

Output:

enter image description here

Note: It doesn't require any Nuget package

Way: 2 When you want to display PDF on your browser from database Model

Solution:

 public ActionResult DisplayPdfOnBrowserFromDatabaseList()
        {
            
            var data = _context.Members.ToList();
            var pdf = data.ToPdf();
            MemoryStream ms = new MemoryStream(pdf);
            return new FileStreamResult(ms, "application/pdf");

        }

Note: To handle this scenario you need to use enter image description here

Way: 3 When you want to download PDF on your browser from database model or existing file

Solution:

public ActionResult DownloadPDFOnBrowser()
    {

        var data = _context.Members.ToList();
        var byteArray = data.ToPdf();

        MemoryStream stream = new MemoryStream(byteArray);

        string mimeType = "application/pdf";
        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = "DatabaseListToPdf.pdf"
        };


    }

Note: As described above we need to add using ArrayToPdf; on top. To handle this scenario you need to use enter image description here

CodePudding user response:

Add a third parameter fileDownloadName to the File method, this specifies the name which will appear for download.

return File(cover, "application/pdf", "MyFile.pdf");

Behind the scenes, this will set the Content-Disposition header with the filename and an attachment directive to tell the browser to download instead of displaying inline.

CodePudding user response:

You could also try following:

This is my controller action:

public async Task<FileResult> DownloadMyFiles(string filetype)
        {
            if (string.IsNullOrEmpty(filetype))
            {
                return null;
            }
            var folderPath = Server.MapPath("/Files");
            var filePath = String.Empty;
            switch (filetype)
            {
                case "pdf":
                    filePath = Path.Combine(folderPath, "mypdffile.pdf");
                    byte[] bytes = System.IO.File.ReadAllBytes(filePath);
                    return File(bytes, "application/octet-stream", "mypdf.pdf");
                case "excel":
                    filePath = Path.Combine(folderPath, "myexcelfile.xlsx");
                    byte[] excel_bytes = System.IO.File.ReadAllBytes(filePath);
                    return File(excel_bytes, "application/octet-stream", "myexcelfile.xlsx");
                case "jpg":
                    filePath = Path.Combine(folderPath, "myjpg.jpg");
                    byte[] image_bytes = System.IO.File.ReadAllBytes(filePath);
                    return File(image_bytes, "image/png", "myjpg.jpg");
                default:
                    return null;
            }

        }

Below is my HTML code :

@Html.ActionLink("Download PDF File", "DownloadMyFiles", "Home", new { filetype = "pdf" }, null)


@Html.ActionLink("Download Excel File File", "DownloadMyFiles", "Home", new { filetype = "excel" }, null)


@Html.ActionLink("Download Image File", "DownloadMyFiles", "Home", new { filetype = "jpg" }, null)

see the output image attached Hopefully my answer will help you. :) Thanks!

  • Related