c# - Request.Files 始终为空

标签 c# asp.net ajax xmlhttprequest

我正在为客户端编写一个 C# ASP.Net MVC 应用程序以将文件发布到其他服务器。我正在使用通用处理程序来处理从客户端到服务器的已发布文件。但在我的处理程序中,System.Web.HttpContext.Current.Request.Files 始终为空(0 计数)。

表单代码:

@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>

}

处理程序:

/// <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

请帮帮我。谢谢。

最佳答案

你需要为xhr设置如下

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

查看帮助链接 - File upload using MVC 4 with Ajax

我明白了,您已经包含了 jquery 库并使用了 jquery 选择器,那么为什么不使用 $.ajax POST 请求?如果您对 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");
  }
});

关于c# - Request.Files 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684689/

相关文章:

c# - 是什么导致 DriveInfo.IsReady 为假?

c# - 带有 System.Object 对象的 XmlSerializer

php - 如何在 php mysql 搜索中加粗关键字?

javascript - jQuery 限制并发 AJAX 请求的数量

c# - ASP.Net HttpCookie 过期

c# - 对 WCF 调用进行单元测试,是否可能以及如何进行?

c# - Json Ajax 参数传递和 Webmethod 未触发

css - 为什么没有应用 Bootstrap 类?

asp.net - 有人能够在 Visual Studio 2015 中使用 Angular 4 Quickstart 吗?

php - 在 PHP 中,在数组中搜索包含子字符串的值的快速方法是什么?