none
How to download File from ASP.NET? RRS feed

  • Question

  • I am new in ASP.NET development. I want to see a good example of how to download a file (exp: .pdf, .txt, .doc etc.) from the server. Suppose a user presses a download button to download a software or a pdf file to his/her local PC. What is the code of the downloading or sending file to the client from the server in ASP.NET? Can you help me about this? 
    Saturday, March 21, 2020 6:03 AM

All replies

  • In its simplest version, the code would be just this:

    Response.Writefile(@"c:\path\filename");

    This will cause the file to be streamed to the browser and the browser will present a dialog asking what to do with the file.

    Optionally, yo may wish to add some http headers to facilitate the way in which the browser handles the file. For example, it would be common to add a header indicating the MIME type of the file:

    Response.Clear();
    Response.ContentType = "application/pdf" Response.Writefile(@"c:\path\myfile.pdf"); Response.End();


    There are several variants and additional headers that you can use. Now that you know that you have to look for "Response.WriteFile", it should be easy for you to find lots of examples across the 'net.

    You would place this code in the Click event handler for your "download" button.

    Saturday, March 21, 2020 9:02 AM
    Moderator
  • Here is a bit of file upload and download code I implemented in an ASP.NET MVC project from an example . It downloaded the to locally to a computer by clicking a file or files.

    You can find something similar for your needs by just searching with Bing or Google.

    You can also post to ASP.NET forums where you can be helped too.

    http://forums.asp.net/

    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.FileProviders;
    using ProgMgmntCore2UserIdentity.Models;
    
    namespace ProgMgmntCore2UserIdentity.Controllers
    {
        public class UploadController : Controller
        {
            private readonly IFileProvider fileProvider;
            private IHostingEnvironment _env;
    
            public UploadController(IFileProvider fileProvider, IHostingEnvironment env)
            {
                this.fileProvider = fileProvider;
                _env = env;
            }
    
            public IActionResult Index(int id, string type)
            {
                return View();
            }
    
            [HttpPost]
            public async Task<IActionResult> UploadFile(IFormFile file)
            {
                var webRoot = _env.WebRootPath;
    
                if (file == null || file.Length == 0)
                    return Content("file not selected");
    
                var path = Path.Combine(webRoot + "\\" + GetFileName(file));
    
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
    
                return RedirectToAction("Files");
            }
    
            [HttpPost]
            public async Task<IActionResult> UploadFiles(List<IFormFile> files)
            {
                var webRoot = _env.WebRootPath;
    
                if (files == null || files.Count == 0)
                    return Content("files not selected");
    
                foreach (var file in files)
                {
                    var path = Path.Combine(webRoot + "\\" + GetFileName(file));
    
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
    
                return RedirectToAction("Files");
            }
    
            [HttpPost]
            public async Task<IActionResult> UploadFileViaModel(FileInputModel model)
            {
                if (model == null ||
                    model.FileToUpload == null || model.FileToUpload.Length == 0)
                    return Content("file not selected");
    
                var path = Path.Combine(
                            Directory.GetCurrentDirectory(), "Upload",
                            model.FileToUpload.GetFilename());
    
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await model.FileToUpload.CopyToAsync(stream);
                }
    
                return RedirectToAction("Files");
            }
    
            public IActionResult Files()
            {
                var model = new FilesViewModel();
                foreach (var item in this.fileProvider.GetDirectoryContents(""))
                {
                    model.Files.Add(
                        new FileDetails { Name = item.Name, Path = item.PhysicalPath });
                }
                return View(model);
            }
    
            public async Task<IActionResult> Download(string filename)
            {
                if (filename == null)
                    return Content("filename not present");
    
                var path = Path.Combine(
                                Directory.GetCurrentDirectory(),
                                "wwwroot", filename);
    
                var memory = new MemoryStream();
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;
                return File(memory, GetContentType(path), Path.GetFileName(path));
            }
    
            private string GetContentType(string path)
            {
                var types = GetMimeTypes();
                var ext = Path.GetExtension(path).ToLowerInvariant();
                return types[ext];
            }
    
            private Dictionary<string, string> GetMimeTypes()
            {
                return new Dictionary<string, string>
                {
                    {".txt", "text/plain"},
                    {".pdf", "application/pdf"},
                    {".doc", "application/vnd.ms-word"},
                    {".docx", "application/vnd.ms-word"},
                    {".xls", "application/vnd.ms-excel"},
                    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
                    {".png", "image/png"},
                    {".jpg", "image/jpeg"},
                    {".jpeg", "image/jpeg"},
                    {".gif", "image/gif"},
                    {".csv", "text/csv"}
                };
            }
    
            private string GetFileName(IFormFile file)
            {
                var filepath = file.GetFilename();
                var startpos = filepath.LastIndexOf("\\") + 1;
                var len = filepath.Length;
    
                var thelen = len - startpos;
    
                return filepath.Substring(startpos, thelen);
            }
        }
    }


    • Edited by DA924x Saturday, March 21, 2020 1:51 PM
    Saturday, March 21, 2020 1:49 PM
  • Hi SHAKIR820,
    As Alberto Poblacion said, you can put the code in the button click event.
    Here is a simple code example you can refer to. 

    private void Button1_click(object sender, System.EventArgs e)
    {
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
        Response.TransmitFile(Server.MapPath("~/doc/test.pdf"));
        Response.End();
    }

    There are some more code examples in these threads you can refer to.
    [How to download a file using ASP.NET]
    [How to download file with asp.net on buttton's onClick event?]
    [ASP.NET file download from server]
    Hope these are helpful to you.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 23, 2020 8:20 AM