asp.net核心上传文件作为表单的一部分

时间:2019-03-21 12:35:49

标签: asp.net asp.net-mvc asp.net-core

尝试上传文件作为表单的一部分并将其存储在wwwroot中的文件夹中,然后将该文件的URL以及表单的其他详细信息存储在sql服务器数据库表中?如果有人有任何想法,那将是极大的应用。我已经使用了此代码,但是它不存储任何内容。但是,当我创建一个新的新项目时,我设法使该代码正确运行,但似乎无法使其在该工作项目中正常工作。不知道这与我是否拥有存储库有关,而我创建的确实可以正常工作的新项目没有任何存储库。这是我能想到的唯一区别。有什么想法吗?

//型号

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>

1 个答案:

答案 0 :(得分:0)

您可以使用IFormFile来接收文件。然后使用EF core将文件路径URL保存到数据库中。记住要创建一个myFiles文件夹,首先将上传的文件保存在wwwroot下。

您可以参考File uploads in 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();
    }
}