在ASP.net MVC追赶AJAX文件上传(HTML5)文件上传、net、ASP、MVC

2023-09-11 01:16:13 作者:社会扛把子

在什么这里是哪里呢? Ajax调用没有达到动作

What is wrong in here? The ajax call is not reaching the action

服务器端:

    [HttpPost]
    public ActionResult UploadFile(long someID, HttpPostedFileBase myFile)
    {
        return "hello";
    }

客户端HTML:

Client side html:

<form id="my-form" method="post" action="" enctype="multipart/form-data">
     <input type="hidden" name="someID" value="156" />
     <input type="file" name="myFile" />
</form>

客户端的JavaScript:

Client side javascript:

$.ajax({
    async: true,
    type: 'POST',
    url: '/MyController/UploadFile/',
    data: new FormData($('#my-form')),
    success: function (data) {},
    cache: false,
    contentType: false,
    processData: false
});

这种通过AJAX上传的应该是可能在某些浏览器。

This kind of upload via ajax should be possible in some browsers.

我得到这个服务器端错误: 参数字典包含非可空类型'System.Int64'参数'someID空条目(...)

I'm getting this serverside error: The parameters dictionary contains a null entry for parameter 'someID' of non-nullable type 'System.Int64' (...)

如果我改变行动UploadFile(),不带参数,Ajax调用进入动作,但我怎么恢复发布的数据?

If I change the action to UploadFile(), with no parameters, the ajax call enters the action, but then how do I recover the posted data?

推荐答案

好了,最后做这样的:

服务器端:

[HttpPost]
public ActionResult UploadFile(long someID)
{
    var file = Request.Files[0];
    return "hello";
}

客户端HTML:

Client side html:

 <form method="post" action="">
     <input type="hidden" id="someID" value="156" />
     <input type="file" id="myFile" />
 </form>

客户端的JavaScript:

Client side javascript:

var blah = new FormData();
blah.append("file", $("#myFile")[0].files[0]);

$.ajax({
    async: true,
    type: 'POST',
    url: '/MyController/UploadFile/?someID='+ $("#someID").val(),
    data: blah,
    success: function (data) {},
    cache: false,
    contentType: false,
    processData: false
});

正如你所看到的, HTML表单竟然没有necesary,无论是加密类型。 该someID事情是由URL通过,该文件被逮住的Request.Files

As you can see, the html form isn't even necesary, neither the enctype. The someID thing is passed by the URL and the file is catched in Request.Files

 
精彩推荐