简体   繁体   中英

File Upload ASP.NET MVC Not Working

I have tried my best however HttpPostedFileBase filee is always null

Controller Action

 public ActionResult UploadFile(HttpPostedFileBase filee)
        {
            try
            {
                if (filee.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(filee.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    filee.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }

Razor View

@{
    ViewBag.Title = "UploadFile";
}

<h2>UploadFile</h2>

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
        <input type="submit" value="Upload" />

        @ViewBag.Message

    </div>


}  

public ActionResult UploadFile(HttpPostedFileBase filee)的参数名称更改为public ActionResult UploadFile(HttpPostedFileBase file)或将输入名称@Html.TextBox("file", "", new { type = "file" })更改为@Html.TextBox("filee", "", new { type = "file" })

You have to use same name of yor input field as your HttpPostedFileBase object name while you are working on loosly type view !

Example :

    @{
        ViewBag.Title = "UploadFile";
    }

    <h2>UploadFile</h2>

    @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

        <div>
            @Html.TextBox("filee", "", new { type = "file" }) <br />
            <input type="submit" value="Upload" />

            @ViewBag.Message

        </div>

}  

Or If you don't want to use same names ? you just have to use a tightly coupled view type view

Tightly
Example:

@model PROJECTNAME.Models.MODELNAME

        @{
            ViewBag.Title = "UploadFile";
        }

        <h2>UploadFile</h2>

        @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {

            <div>
                @Html.TextBox(model => model.YOURCOLUMNNAME , "", new { type = "file" }) <br />
                <input type="submit" value="Upload" />

                @ViewBag.Message

            </div>

    }  

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