Request.Files 始终为空

Posted

技术标签:

【中文标题】Request.Files 始终为空【英文标题】:Request.Files is always null 【发布时间】:2014-12-28 08:45:22 【问题描述】:

我正在编写一个 C# ASP.Net MVC 应用程序供客户端将文件发布到其他服务器。我正在使用通用处理程序来处理从客户端到服务器的发布文件。但在我的处理程序中,System.Web.HttpContext.Current.(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

请帮助我。谢谢。

【问题讨论】:

【参考方案1】:

终于找到问题所在了。

由于某种原因,我的控制器中的代码var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; 永远无法正常工作。我的ajax没有问题。 我将控制器中的代码更改为如下所示,现在可以找到它。

[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


【讨论】:

没有为我解决它,我正在使用上面的服务器端代码,并让您的 xhr 对象执行与您类似的 xhr.send(data)Request.Files.Count 仍为 0。【参考方案2】:

您需要为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");
  
);

【讨论】:

我一开始用的是ajax版本,结果不行。【参考方案3】:

要发布文件,发布数据必须是 multipart/form-data 编码类型。所以你必须设置请求头如下:

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

请看样例:Upload File With Ajax XmlHttpRequest

【讨论】:

试过了,还是不行。在我的表单标题旁边已经包含了代码 <...enctype>。

以上是关于Request.Files 始终为空的主要内容,如果未能解决你的问题,请参考以下文章

Python烧瓶使用ajax request.files上传文件为空

无法获取 request.FILES django

通过 AJAX 发送图像文件。 request.FILES 为空?

flask上传文件时request.files为空的解决办法

从 jQuery 传递到 ASP.NET 代码时,Request.Files 集合为空

django中处理文件上传文件