简体   繁体   中英

When I try to upload a file in ASP.NET MVC, it shows as null

For some reason the paramater OriginalLocation is always null in the following code. What am I doing wrong?

Controller:

 [HttpPost]
 public ActionResult File(HttpPostedFileBase OriginalLocation, FileModel model)
 {
     byte[] binaryData = null;
     if (OriginalLocation != null && OriginalLocation.ContentLength > 0)
     {
         binaryData = new byte[OriginalLocation.ContentLength];
         OriginalLocation.InputStream.Read(binaryData, 0,
                          OriginalLocation.ContentLength);
         if (model.UploadFile(OriginalLocation))
         {
             return RedirectToAction("Profile", "Account");
         }
     }
 return View();
 }

View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master" Inherits="System.Web.Mvc.ViewPage<NISE.Web.TestForum.Models.File.FileModel>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
Find upload
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

<% using (Html.BeginForm("File", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
   { %> 
<%--<form enctype="multipart/form-data" method="post" action="/File/File">--%>

      <input type="file" name="OriginalLocation" id="OriginalLocation"  />

    <input type="submit" value="Upload" />

<%--</form>--%>
<%} %>

</asp:Content>

Model:

public bool UploadFile(HttpPostedFileBase OriginalLocation)
    {
        if (OriginalLocation != null)
        {
            var filename = Path.GetFileName(OriginalLocation.FileName);
            OriginalLocation.SaveAs(@"C:\" + filename);
            return true;
        }
        return false;
    }

I think you just need to remove the FileModel model parameter from your Action method. Nothing is being passed to it, and so it's screwing up model binding (unless there is more code in the view that you have deleted from your post).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM