首页 > 解决方案 > 使用输入字段上传文件

问题描述

asp.net-mvc我使用和创建了一个网络应用程序Jquery

当我添加下面的代码时,我的应用程序会自动停止运行而不会引发任何错误,我不知道它是我的visual studio 19还是IIS哪个正在崩溃

<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">

为了验证我创建了一个asp.net mvc示例项目并将上面的代码粘贴到索引页面中,但同样的问题出现了

图片

我能做些什么来解决这个问题?

标签: asp.net-mvciisvisual-studio-2019

解决方案


您可以尝试使用以下代码:

查看(索引.cshtml):

            <input type="file" id="FileUpload1" />
            <input type="button" id="btnUpload" value="Upload Files" />

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>

$(document).ready(function(){
    $('#btnUpload').click(function () {

        // Checking whether FormData is available in browser
        if (window.FormData !== undefined) {

            var fileUpload = $("#FileUpload1").get(0);
            var files = fileUpload.files;

            // Create FormData object
            var fileData = new FormData();

            // Looping over all files and add it to FormData object
            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }

            // Adding one more key to FormData object
            fileData.append('username', 'test');

            $.ajax({
                url: '/Home/UploadFiles',
                type: "POST",
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                data: fileData,
                success: function (result) {
                    alert(result);
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        } else {
            alert("FormData is not supported.");
        }
    });
});
</script>

控制器(HomeController.cs):

  [HttpPost]
    public ActionResult UploadFiles()
    {
        // Checking no of files injected in Request object  
        if (Request.Files.Count > 0)
        {
            try
            {
                //  Get all files from Request object  
                HttpFileCollectionBase files = Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                    //string filename = Path.GetFileName(Request.Files[i].FileName);  

                    HttpPostedFileBase file = files[i];
                    string fname;

                    // Checking for Internet Explorer  
                    if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                    {
                        string[] testfiles = file.FileName.Split(new char[] { '\\' });
                        fname = testfiles[testfiles.Length - 1];
                    }
                    else
                    {
                        fname = file.FileName;
                    }

                    // Get the complete folder path and store the file inside it.  
                    fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
                    file.SaveAs(fname);
                }
                // Returns message that successfully uploaded  
                return Json("File Uploaded Successfully!");
            }
            catch (Exception ex)
            {
                return Json("Error occurred. Error details: " + ex.Message);
            }
        }
        else
        {
            return Json("No files selected.");
        }
    }

确保您的 IIS 站点包含上传文件夹和足够的权限来访问该文件夹。

在此处输入图像描述

如果您仍然遇到同样的问题,请尝试使用不同的浏览器。检查事件查看器日志或尝试收集 dup 并使用 DebugDiag 工具分析转储。


推荐阅读