【问题标题】:Object Referenced is Null-- HTTPPostedFiles [duplicate]引用的对象为空 - HTTPPostedFiles [重复]
【发布时间】:2020-12-13 01:40:36
【问题描述】:

大家好,

我正在尝试将图像上传到文件夹并使用 ASP.NET MVC 代码优先方法将路径 URL 保存在数据库中。

在保存 URL 路径时,它返回 Object referenced Null。

下面是表单保存时调用的动作方法。

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Account_Number,Title,Firstname,Othername,Surname,Phone_Number,Bank_AccountName, Bank_Fullname, img_Passport")] SavingsAccount savingsAccount, HttpPostedFileBase postedFile)
    {
        Thread.Sleep(2000);
        
        //Extract Image File Name.
        string fileName = "1000000005";

        //Set the Image File Path.
        string filePath = "~/Images/Uploads/SavingsAccount/" + fileName;

        //Save the Image File in Folder.
        postedFile.SaveAs(Server.MapPath(filePath));
        

        if (ModelState.IsValid)
        {
            savingsAccount.Account_Number = Account_No;
            savingsAccount.Account_Type = "Savings Account";
            savingsAccount.Account_Balance = 0;
            savingsAccount.Date_Opened = Convert.ToDateTime(DateTime.Now.ToString());
            savingsAccount.Opened_By = User.Identity.Name;
            savingsAccount.img_Passport = filePath; //Insert the Passport URL Path to database
            db.SavingsAccounts.Add(savingsAccount);
            db.SaveChanges();
     
            return View("DisplaySuccessMessage");
        }

        return View(savingsAccount);
    }

当我使用断点检查发送的值时,Posted 文件被视为 Null。

我做错了吗?

【问题讨论】:

  • 我认为这是因为在view 页面中没有将new { enctype = "multipart/form-data" }) 参数添加到@html.BeginForm。使用此“@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { enctype = "multipart/form-data" }))" 创建表单
  • 正是问题所在。非常感谢

标签: c# asp.net-mvc


【解决方案1】:

在 ASP.NET Core 中使用上传文件,例如 this article

public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            var filePath = Path.GetTempFileName();

            using (var stream = System.IO.File.Create(filePath))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // Process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2016-10-04
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多