在MVC中通过ajax上传文件时,我的Request.Files in action side始终为null

时间:2017-10-06 13:56:29

标签: javascript jquery ajax asp.net-mvc

我需要在MVC中通过ajax模式上传图像。我使用此方法在Js代码中一切正常,它获取formdata并且ajax请求被正确发送到控制器但在我的控制器中我得到Request.File [& #34; myfile"]总是空的...我到处搜索解决方案,但没有找到请帮助我这么紧急...谢谢所有 这是我的js代码:



		function UploadImage() {
			var data = new FormData();
			var files = $("#myfile").get(0).files;
			if (files.length > 0) {
				data.append("MyImages", files[0]);
			}

		$.ajax({
				url: "@Url.Action("SaveFile","Home")",
				type: "POST",
				processData: false,
				contentType: false,
				enctype: 'multipart/form-data',
				data: {},
				success: function (response) {
					//code after success
					console.log(response);
					alert(response);
				},
				error: function (er) {
					alert(er);
				}

			});
		}
	
Html:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
	<title>upload</title>
	<link href="~/Content/bootstrap.css" rel="stylesheet" />
	<script src="~/Scripts/jquery-1.10.2.min.js"></script>
	<script src="~/Scripts/bootstrap.min.js"></script>
	<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
	
</head>
<body>
<div class="row">
	<div class="container">
		<div>
			file:<input type="file" id="myfile" style="display: block"/>
			<br />
			<input type="button" value="save" id="btnUpload" onclick="UploadImage()"/>
		</div>
	</div>
</div>
</body>
</html>
&#13;
&#13;
&#13;

和我的行动:

        [HttpPost]
    public JsonResult SaveFile()
    {
        var uniqueName = "";
        if (Request.Files["myfile"] != null)
        {
            var file = Request.Files["myfile"];
            if (file.FileName != "")
            {
                var ext = System.IO.Path.GetExtension(file.FileName);

                uniqueName = System.Guid.NewGuid().ToString() + ext;

                var rootPath = Server.MapPath("~/Upload/");

                var fileSavePath = System.IO.Path.Combine(rootPath, uniqueName);
                file.SaveAs(fileSavePath);
            }
        }

        return Json(new
        {
            success=false,
            name=uniqueName
        },JsonRequestBehavior.AllowGet);
    }

1 个答案:

答案 0 :(得分:0)

遵循与您的代码非常相似的example

更改此

data: {}

由此

data: data

示例代码视图

<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', ‘Manas’);  

            $.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> 

示例代码控制器

[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.");  
    }  
}