Request.files is Empty in MVC file upload

2019-01-26 20:21发布

问题:

I have the same issue

@using (Html.BeginForm("CreateRequest", "SupportRequest", FormMethod.Post, new { id = "frmStemplate", enctype = "multipart/form-data" }))
{
  <td><input type="file" name="FirstFile" id="FirstFile" class="button"  /> 
  <input  type="button" class="button" id="FirstFileupload"  value="upload" onclick="Javascript:DocumentUpload();"/>
}

<script language="javascript" type="text/javascript">
    function DocumentUpload()
    {
        var BrowseFile = $('#FirstFile').val();

        if (BrowseFile != null && BrowseFile != "") {
            alert(BrowseFile);
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '@Url.Content("~/SupportRequest/UploadFiles")?fileElementId=' + BrowseFile,
                success: function (data) {
                    alert('Hi'); //debugger;
                    if (data.Result == "SUCCESS") {
                        alert('Hi');
                    }
                    else {
                        ShowInfo('Document Uploaded Successfully');
                    }
                }
            });
        }
    }
</script>

On the controller side, I have:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFiles(string fileElementId, FormCollection formColl)
{
    var FirstFile = Request.Files;
    foreach (string upload in Request.Files)
    {
        if (!Request.Files[upload].HasFile()) continue;
        string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
        string filename = Path.GetFileName(Request.Files[upload].FileName);
        Request.Files[upload].SaveAs(Path.Combine(path, filename));
    }
    return Json(new { Filename = "" });
}

But my Request.Files is always null.

I tried several things, like changing the code to Request.Files["FirstFile"], etc. Each time, the file collection is empty.

回答1:

You need to use HttpPostedFileBase in controller action parameters inorder to get the filedata that you have posted.

Please read this full article by Phil Haack



回答2:

Since you are creating the post of the data you will need to post the file data. see this post:

How can I upload files asynchronously?



回答3:

I did the different way using form collection that can easily Upload files.Like u did add that line inside begin form in cshtml page.

public ActionResult Create([Bind(Include="Id,Name,Pic,ActiveStatus")] FormCollection form)
    {

        string Pic = "";
        var file = Request.Files[0];

        if (file.ContentLength > 0)
        {
            Pic = string.Format("~/Uploads/Category/{0}", file.FileName);
            file.SaveAs(HttpContext.Server.MapPath(Pic));

        }

        ItemCategory obj = new ItemCategory
        {
            Name = form["Name"].ToString(),
            Pic = file.FileName

        };

        db.ItemCategories.Add(obj);
        db.SaveChanges();
        return RedirectToAction("Index");