ASP.NET CORE 2.0下载/上传文件[附源码]

本文介绍如何在ASP.NET Core MVC中实现文件上传和下载功能。通过更新Startup类添加MVC服务和中间件,创建控制器和操作方法处理文件上传与下载请求。使用HTML表单进行文件选择和提交,确保表单的编码类型设置为multipart/form-data。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

How to upload and download files in ASP.NET Core MVC.

Solution

In an empty project update Startup class to add services and middleware for MVC:

 public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddSingleton<IFileProvider>(
                new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
 
            services.AddMvc();
        }
 
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Add a controller and action methods to upload and download file:

        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("file not selected");
 
            var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot", 
                        file.GetFilename());
 
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
 
            return RedirectToAction("Files");
        }
 
        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));
        }

Add a razor page with HTML form to upload file:

<form asp-controller="Home" asp-action="UploadFile" method="post"
      enctype="multipart/form-data">
    
    <input type="file" name="file" />
    <button type="submit">Upload File</button>
</form>

Discussion

Uploading

ASP.NET Core MVC model binding provides IFormFile interface to upload one or more files. The HTML form must have encoding type set to multipart/form-data and an input element with typeattribute set to fil.

You could also upload multiple files by receiving a list of IFormFile in action method and setting inputelement withmultiple` attribute:

// In Controller
[HttpPost]
public async Task<IActionResult> UploadFiles(List<IFormFile> files)
 
// In HTML
<input type="file" name="files" multiple />

You could also have IFormFile as a property on model received by action method:

    public class FileInputModel
    {
        public IFormFile FileToUpload { get; set; }
    }
    [HttpPost]
    public async Task<IActionResult> UploadFileViaModel(FileInputModel model)

Note: name on input elements must match action parameter name (or model property name) for model binding to work. This is no different than model binding of simple and complex types.

Downloading

Action method needs to return **FileResult** with either a **stream**, **byte[]** or virtual path of the file. You will also need to know the **content-type** of the file being downloaded. Here is a sample (quick/dirty) utility method:

        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"}
            };
        }

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.FileUpload

4624570-7ad1442474a63a1f.gif
好书推荐、视频分享,与您一起进步
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值