首页 > 解决方案 > asp.net core 上传文件作为表单的一部分

问题描述

尝试将文件作为表单的一部分上传并将其存储在 wwwroot 的文件夹中,然后将文件的 url 与表单的其他详细信息一起存储在 sql server 数据库表中?如果有人有任何想法,将不胜感激。我已经使用了这段代码,但它不存储任何东西。然而,当我创建一个全新的项目时,我设法让代码正常工作,但似乎无法让它在这个工作项目中工作。不确定这是否与我有存储库和我创建的新项目没有任何存储库有关。这是我能想到的唯一区别。有任何想法吗?

//模型

namespace PostProjectEvaluations.Web.Models
{
    public partial class Projects
    {
        [Key]
        public int ProjectId { get; set; }
        [Required]
        [StringLength(300)]
        public string Name { get; set; }
        [Required]
        [StringLength(50)]
        public string Manager { get; set; }

        public string FilePath { get; set; }

    }
    public class ProjectsVM
    {
        public string Name { get; set; }
        public IFormFile File { get; set; }
    }

//控制器

    namespace PostProjectEvaluations.Web.Controllers
    {
        public class projectsController : Controller
        {
            private readonly IApplicationRepository ApplicationRepository;
            private readonly PostProjectEvaluationsContext _context;
            private IHostingEnvironment mxHostingEnvironment { get; set; }
            private object objproject;

            public projectsController(IApplicationRepository applicationRepository,
                IHostingEnvironment hostingEnvironment, PostProjectEvaluationsContext context)
            {
                mxHostingEnvironment = hostingEnvironment;
                ApplicationRepository = applicationRepository;
                _context = context;
            }


            public IActionResult Index()
            {
                ViewBag.dataSource = ApplicationRepository.GetAllProjects().ToList();
                var projects = ApplicationRepository.GetAllProjects();
                return View(projects);
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Index(ProjectsVM projectsVM)
            {
                if (projectsVM.File != null)
                {
                    //upload files to wwwroot
                    var fileName = Path.GetFileName(projectsVM.File.FileName);
                    var filePath = Path.Combine(mxHostingEnvironment.WebRootPath, "Uploads", fileName);


                    using (var fileSteam = new FileStream(filePath, FileMode.Create))
                    {
                        await projectsVM.File.CopyToAsync(fileSteam);
                    }
                    //your logic to save filePath to database, for example

                    Projects projects = new Projects();
                    projects.Name = projectsVM.Name;
                    projects.FilePath = filePath;

                    _context.Projects.Add(projects);
                    _context.SaveChanges();
                }
                else
                {

                }
                return View("Index");
            }
 public IActionResult Details(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            return View(project);
        }

        [HttpGet]
        public IActionResult Create()
        {

            var project = new Projects();
            return View(project);
        }

        [HttpPost]
        public IActionResult Create(Projects projects)
        {
            ApplicationRepository.Create(projects);
            return RedirectToAction("Index");

        }



        public IActionResult Delete(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            ApplicationRepository.Delete(project);
            return RedirectToAction("Index");
        }


        [HttpGet]
        public IActionResult Edit(int id)
        {
            var project = ApplicationRepository.GetProjects(id);
            //mxApplicationRepository.SaveChangesAsync();
            return View(project);
        }
        [HttpPost]
        public IActionResult Edit(Projects projects)
        {
            ApplicationRepository.Edit(projects);
            //mxApplicationRepository.SaveChangesAsync();
            return RedirectToAction("Index");
        }


    }

}

//看法

      <form enctype="multipart/form-data" asp-controller="Projects" asp-action="Create" method="post" class="form-horizontal">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-body">
                <h3 class="form-section">Project Info</h3>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label col-md-3">Project Name</label>
                            <div class="col-md-9">
                                <input asp-for="Name" class="form-control" placeholder="Name">
                                <span asp-validation-for="Name" class="text-danger"></span>
                            </div>
                        </div>
                    </div>
                    <!--/span-->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label col-md-3">Project Manager</label>
                            <div class="col-md-9">
                                <input asp-for="Manager" class="form-control" placeholder="Name">
                            </div>
                        </div>
                    </div>
                    <!--/span-->
                </div>

                <!--/span-->
            </div>
            <h3 class="form-section">Project Files</h3>
            <!--/row-->
            <div class="row">
                <div>
                    <div class="col-md-6">
                        <div class="col-md-10">
                            <p>Upload one or more files using this form:</p>
                            <input type="file" name="files" multiple />
                        </div>
                    </div>
                </div>
                <div>
                </div>
                </div>

                <div class="form-actions right">
                    <input type="submit" class="btn blue-assembly" name="submitButton" value="Save" />
                    <a asp-action="Index" class="btn default" onclick="cancelClick()">Cancel</a>
                </div>
</form>

标签: asp.netasp.net-mvcasp.net-core

解决方案


您可以使用IFormFile接收文件。然后使用 EF 核心将文件路径 url 保存到您的数据库。请记住首先创建一个myFiles文件夹来保存上传的文件wwwroot

可以参考ASP.NET Core 文件上传教程

下面是一个简单的演示:

楷模:

public class Engineer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FilePath { get; set; }
}
public class EngineerVM
{
    public string Name { get; set; }
    public IFormFile File{ get; set; }
}

看法:

@model EngineerVM
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <input type="text" asp-for="Name" />
    </div>
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="file"/>
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Save" />
    </div>
</div>
</form>

控制器:

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnv;
    private readonly ApplicationDbContext _context;

    public HomeController(IHostingEnvironment hostingEnv,ApplicationDbContext context)
    {
        _hostingEnv = hostingEnv;
        _context = context;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(EngineerVM engineerVM)
    {
        if (engineerVM.File != null)
        {
            //upload files to wwwroot
            var fileName = Path.GetFileName(engineerVM.File.FileName);
            var filePath = Path.Combine(_hostingEnv.WebRootPath, "images", fileName);

            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await engineerVM.File.CopyToAsync(fileSteam);
            }
            //your logic to save filePath to database, for example

            Engineer engineer = new Engineer();
            engineer.Name = engineerVM.Name;
            engineer.FilePath = filePath;

            _context.Engineers.Add(engineer);
            await _context.SaveChangesAsync();
        }
        else
        {

        }
        return View();
    }
}

推荐阅读