微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – Request.Files始终为null

我正在编写一个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

请帮我.谢谢.

解决方法:

最后,我发现了问题.

代码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

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐