locked
How to make function make download file on asp.net core 2.2 Web API ? RRS feed

  • Question

  • User696604810 posted

    I work on project use .net core 2.2 visual studio 2017 Web API 

    i Need to make function download file 

    Give function path and download file as below 

    I need to make function do download file on .net core 2.2 as 

            public void DownloadOutPut(string path)
            {
                try
                {
    
    
                    if (path != "")
                    {
    
    
                        System.IO.FileInfo file = new System.IO.FileInfo(path);
                        if (file.Exists)
                        {
    
                            Response.Clear();
                            Response.ContentType = "application/octet-stream";
                            Response.AppendHeader("Content-Disposition", "attachment;filename = " + file.Name + "");
                            Response.TransmitFile(path);
    
    
                        }
    
                        Response.End();
                    }
                }
                catch (Exception ex)
                {
    
                    throw;
                }
            }

    above done on asp.net  web form I need to  do function similar to it but on .net core 2.2 

    so How to do it please ?

    Wednesday, November 18, 2020 12:33 AM

All replies

  • User1312693872 posted

    Hi, ahmedbarbary

    Based on your former post, I added a download function , you can check this demo:

    Controller:

            private readonly IFileProvider fileProvider;             
    
            public HomeController(IFileProvider fileProvider)
            {
                this.fileProvider = fileProvider;
            }
    
            public IActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public IActionResult Upload(IFormFile file)
            {
                    var DisplayFileName = Request.Form.Files[0].FileName;
                    string DirectoryCreate = "FilesHere";
                    if (!Directory.Exists(DirectoryCreate))
                    {
                        Directory.CreateDirectory(DirectoryCreate);
    
                    }
                    if (DisplayFileName.Length > 0)
                    {
                        var dbPath = Path.Combine(DirectoryCreate, DisplayFileName);
                        using (var stream = new FileStream(dbPath, FileMode.Create))
                        {
                            Request.Form.Files[0].CopyTo(stream);
                        }
                    return RedirectToAction("Files");
                    }
                    else
                    {
                        return BadRequest();
                    }
            }
    
            public IActionResult Files() //save files and show it in this demo
            {
                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)  //download function
            {
                if (filename == null)
                    return Content("filename not present");
    
                var path = Path.Combine(
                               Directory.GetCurrentDirectory(),
                               "FilesHere", filename);  //get the file
    
                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"} }; }

    Index View:

    @model MyModel
    
    <form method="post" enctype="multipart/form-data" asp-action="Upload">
        <input type="file" asp-for="Upload"/>
        <input type="submit" value="submit"/>
    </form>

    'Files' view:

    @model FilesViewModel
    
    @foreach (var item in Model.Files)
    {
    <li>
        <a asp-action="Download"
           asp-route-filename="@item.Name">
            @item.Name
        </a>
    </li>}

    FilesViewModel:

    public class FilesViewModel
        {
            public List<FileDetails> Files { get; set; }
                = new List<FileDetails>();
        }
        public class FileDetails
        {
            public string Name { get; set; }
            public string Path { get; set; }
        }

    MyModel:

    public class MyModel
        {
            public IFormFile Upload { get; set; }
        }

    And you should add the following code to ConfigureServices()

    services.AddSingleton<IFileProvider>(new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "FilesHere")));

    Result:

    Best Regards,

    Jerry Cai

    Wednesday, November 18, 2020 6:46 AM
  • User1312693872 posted

    Hi, ahmedbarbary

    Have you solved your problem, do you have any problems when using my code, welcome to ask.

    Best Regards,

    Jerry Cai

    Monday, November 23, 2020 3:17 AM