天天看点

asp.net core MVC 上传单文件与多文件

以上传 图片为例

1.model中 Student模型 增加一个string类型的 文件名称 属性,用于记录文件名 如:

public class Student //Model名称
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public ClassNameEnum ClassName { get; set; }

        public string Email { get; set; }

        public string PhotoFileName { get; set; } //数据库中字段
    }
           

2.在 ViewModel 中把 PhotoFileName 属性 返回值 改为 IFormFile 类型,用于接受 文件 其他属性不变 如:

public class StudentPhoto  //ViewModel名称
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public ClassNameEnum ClassName { get; set; }

        public string Email { get; set; }

        public IFormFile PhotoFileName { get; set; } //改变
    }
           

3.前端视图 添加前端代码,asp-for="@Model.PhotoFileName" 会自动生成 Tpye=file,如:

<input asp-for="@Model.PhotoFileName" class="form-control custom-file-input" />
           

4.构造函数 注入 IWebHostEnvironment 用于获取 asp.net core MVC WebRootPath(网站根目录)  本机的wwwroot路径

private readonly IWebHostEnvironment hostEnvironment;

        public HomeController(IWebHostEnvironment hostEnvironment)
        {
            this.hostEnvironment = hostEnvironment;
        }
           

5.在控制器 方法中 添加 操作 如:

[HttpPost]
        public IActionResult Create(StudentPhoto model)
        {
            if (ModelState.IsValid)
            {   
                //将 webRoot路径与 images 路径合并到一起
                string ImgWebPath = Path.Combine(hostEnvironment.WebRootPath, "images");

                //生成一个唯一的 文件名
                string fileName = Guid.NewGuid().ToString() + "_" + model.PhotoFileName.FileName;

                //组合绝对路径:images路径+文件名
                string FullName = Path.Combine(ImgWebPath, fileName);

                //将文件 拷贝到 images文件夹中
                model.PhotoFileName.CopyTo(new FileStream(FullName, FileMode.Create));
                Student student = new Student
                {
                    Name = model.Name,
                    Email = model.Email,
                    ClassName = model.ClassName,
                    PhotoFileName = fileName
                };
                //添加到数据库中
                Student newStudent = _studentRepository.AddStudent(student);
                return View("OneStudent", newStudent);
            }
            return View();
        }
           

多文件上传

1.改变  第2步 ViewModel 文件为:

public class StudentPhoto  //ViewModel名称
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public ClassNameEnum ClassName { get; set; }

        public string Email { get; set; }

        public List<IFormFile> PhotoFileName { get; set; } //多文件上传
    }
           

2.修改 第3步 前端视图 增加 multiple  属性,支持多文件上传

<input asp-for="@Model.PhotoFileName" multiple class="form-control custom-file-input" />
           

最后 需要在 form表单添加 enctype 如: <form enctype="multipart/form-data">

继续阅读