asp.net-mvc - 在Asp.Net Core中上传图片?

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

我想在“wwwroot/uploads/img”文件夹中上传图像,但出现错误。我编写了以下代码:

创建 View :

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

Controller

    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\\");

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

最佳答案

我解决了。我知道我最初不好

_appEnvironment

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

感谢@Shyju 用户。

关于asp.net-mvc - 在Asp.Net Core中上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185920/

相关文章:

c# - 将 Command 对象/Reader 传递给函数是个好主意吗?

c# - 在 ASP.NET MVC (3) 中使用数据注释验证时是否可以生成属性的计算值?

ASP.NET MVC : Exception rendering view in new thread

visual-studio - 在Visual Studio DNX项目(.xproj)中使用代码分析

c# - 如何从现有的创建 IServiceCollection?

c# - 异常 : Correlation failed. 未知位置

c# - 如何使用对象上下文在 Entity Framework 中使用批量插入?

java - FTP 列表命令抛出 MalformedServerReplyException : Truncated server reply

python - 在 Django 中上传文件时出现 OSError

file-upload - 在保存文件之前使用 MultipartFormDataStreamProvider 检测文件大小?