Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net mvc - Request.files is Empty in MVC file upload

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...