在Asp.Net Core上传图片?

时间:2017-11-08 17:22:08

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

我想在“wwwroot / uploads / img”文件夹中上传图片但我收到错误。我写了以下代码:

创建视图:

@model imageuploader.Models.Employee

<form method="post" enctype="multipart/form-data" asp-controller="Employee" asp-action="Create">

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="FirstName" class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="LastName" Class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="ImageName" type="file" Class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Create" />
    </div>
</div>

型号:

public class Employee
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string ImageName { get; set; }
}

控制器

    private readonly RegisterDBContext _context;
    private readonly IHostingEnvironment _appEnvironment;


    public EmployeeController(RegisterDBContext context, IHostingEnvironment appEnvironment)
    {

        _context = context;
        _appEnvironment = appEnvironment;
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Employee emp)
    {
        if (ModelState.IsValid)
        {
            var files = HttpContext.Request.Form.Files;
            foreach (var Image in files)
            {
                if (Image != null && Image.Length > 0)
                {
                    var file = Image;
                    //There is an error here
                    var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img");
                    if (file.Length > 0)
                    {
                        var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
                        using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                            emp.BookPic = fileName;
                        }

                    }
                }
            }
            _context.Add(emp);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        else
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
        }
        return View(emp);
    }

当我点击提交按钮时,我收到错误(标记错误行),如何在指定路径上传图像或文件?

错误:

NullReferenceException: Object reference not set to an instance of an object.

imageuploader.Controllers.EmployeeController+<Create>d__2.MoveNext() in EmployeeController.cs

                        var uploads = Path.Combine(_appEnvironmen.WebRootPath, "uploads\\img\\");

如何在指定路径中正确上传图片?

2 个答案:

答案 0 :(得分:2)

我解决了它。我明白我最初的不好

  

_appEnvironment

在构造函数中。 通过重复编辑,所有相关代码目前都是正确的。

感谢@Shyju用户。

答案 1 :(得分:0)

以下是在C#Asp.net核心Web应用程序2.1 MVC中上传图像的方法:

首先,我假设您已经创建了一个模型,并将其添加到db中,并且现在可以在控制器中使用。

我创建了一个Person模型 person model

要创建,请获取:

 //Get : Person Create
        public IActionResult Create()
        {
            return View();
        }

发布操作(请参阅屏幕截图) create post action method

最后是视图 Create View

项目输出: Here is the output of my project