简体   繁体   English

Request.Files 始终为空

[英]Request.Files is always null

I'm writing a C# ASP.Net MVC application for client to post files to other server.我正在编写一个 C# ASP.Net MVC 应用程序供客户端将文件发布到其他服务器。 I'm using a generic handler to handle posted files from client to server.我正在使用通用处理程序来处理从客户端到服务器的发布文件。 But in my handler, System.Web.HttpContext.Current.Request.Files always empty (0 count).但在我的处理程序中,System.Web.HttpContext.Current.Request.Files 始终为空(0 计数)。

Form Code:表格代码:

@model ITDB102.Models.UploadFileResultsModels
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div>
    <h1>Upload File</h1>
    <form id="file-form" action="/Files/UploadFile" method="post" data-ajax="false" enctype="multipart/form-data">
        <div><input type="file" id="FilePath" name="FilePath"/>
        <button type="submit">Send File</button></div>
    </form>
</div>

@section scripts{
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">

        // Variable to store your files
        var files;
        var form = document.getElementById('file-form');

        // Add events
        $('input[type=file]').on('change', prepareUpload);

        // Grab the files and set them to our variable
        function prepareUpload(event) {
            files = $('#FilePath').get(0).files;
        }

        form.onsubmit = function (event) {
            uploadFiles(event);
        }

        // Catch the form submit and upload the files
        function uploadFiles(event) {
            event.stopPropagation(); // Stop stuff happening
            event.preventDefault(); // Totally stop stuff happening           

            // Create a formdata object and add the files
            var data = new FormData();
            if (files.lenght > 0)
            {
                data.append('UploadedFiles', files[0], file[0].name);
            }

            //setup request
            var xhr = new XMLHttpRequest();
            //open connection
            xhr.open('POST', '/Files/UploadFile',false);
            xhr.setRequestHeader("Content-Type", files.type);
            //send request
            xhr.send(data);

        }

    </script>

}

Handler:处理程序:

/// <summary>
    /// Uploads the file.
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public virtual ActionResult UploadFile()
    {
        HttpPostedFile myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];

        bool isUploaded = false;
        string message = "File upload failed";

        if (myFile != null && myFile.ContentLength != 0)
        {
            string pathForSaving = Server.MapPath("~/Uploads");
            if (this.CreateFolderIfNeeded(pathForSaving))
            {
                try
                {
                    myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                    isUploaded = true;
                    message = "File uploaded successfully!";
                }
                catch (Exception ex)
                {
                    message = string.Format("File upload failed: {0}", ex.Message);
                }
            }
        }
        return Json(new { isUploaded = isUploaded, message = message }, "text/html");
    }


    #region Private Methods

    /// <summary>
    /// Creates the folder if needed.
    /// </summary>
    /// <param name="path">The path.</param>
    /// <returns></returns>
    private bool CreateFolderIfNeeded(string path)
    {
        bool result = true;
        if (!Directory.Exists(path))
        {
            try
            {
                Directory.CreateDirectory(path);
            }
            catch (Exception)
            {
                /*TODO: You must process this exception.*/
                result = false;
            }
        }
        return result;
    }

    #endregion

Please help me.请帮我。 Thanks.谢谢。

Finally, I found the problem.最后,我发现了问题。

The code var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];代码var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; in my controller is never working for some reason.在我的控制器中由于某种原因永远不会工作。 There is nothing wrong with my ajax.我的ajax没有问题。 I changed my code in the controller as bellow and it's working find now.我将控制器中的代码更改为如下所示,它现在可以正常工作了。

[HttpPost]
    public virtual ActionResult UploadFile()
    {
        //var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];
        //
        bool isUploaded = false;
        string message = "File upload failed";

        for (int i = 0; i < Request.Files.Count; i++ )
        {
            var myFile = Request.Files[i];

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/Uploads");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "File uploaded successfully!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("File upload failed: {0}", ex.Message);
                    }
                }
            }

        }


        return Json(new { isUploaded = isUploaded, message = message }, "text/html");
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Creates the folder if needed.
    /// </summary>
    /// <param name="path">The path.</param>
    /// <returns></returns>
    private bool CreateFolderIfNeeded(string path)
    {
        bool result = true;
        if (!Directory.Exists(path))
        {
            try
            {
                Directory.CreateDirectory(path);
            }
            catch (Exception)
            {
                /*TODO: You must process this exception.*/
                result = false;
            }
        }
        return result;
    }

    #endregion

}

You need to set following for xhr .您需要为xhr设置以下内容。

dataType: 'json',
contentType: false,
processData: false,

See help link - File upload using MVC 4 with Ajax请参阅帮助链接 - 使用 MVC 4 和 Ajax 上传文件

I see that, you have included jquery library and used jquery selectors, so why don't you use $.ajax for POST request?我看到了,您已经包含了jquery库并使用了jquery选择器,那么为什么不使用$.ajax进行POST请求呢? In case you are interested in jquery way, following is the script.如果您对jquery方式感兴趣,以下是脚本。

$.ajax({
  type: "POST",
  url: '/Files/UploadFile',
  data: data,
  dataType: 'json',
  contentType: false,
  processData: false,
  success: function(response) {
    alert('succes!!');
  },
  error: function(param1,param2,param3) {
    alert("errror");
  }
});

I had a similar issue using Asp.Net MVC5.我在使用 Asp.Net MVC5 时遇到了类似的问题。 For me it turned out to be a file size issue which I resolved following suggestions from this posted question .对我来说,它原来是一个文件大小问题,我根据这个发布的问题的建议解决了这个问题

To post a file, the post data must be in multipart/form-data Encoding type.要发布文件,发布数据必须是 multipart/form-data 编码类型。 So you must set request header as below:因此,您必须将请求标头设置如下:

xhr.setRequestHeader("Content-Type","multipart/form-data"); xhr.setRequestHeader("Content-Type","multipart/form-data");

Please see sample: Upload File With Ajax XmlHttpRequest请参阅示例: 使用 Ajax XmlHttpRequest 上传文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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