1

这里有什么问题?
ajax 调用未达到操作

服务器端:

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

客户端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:

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

在某些浏览器中应该可以通过 ajax 进行这种上传。

我收到此服务器端错误:参数字典包含不可为空类型“System.Int64”的参数“someID”的空条目(...)

如果我将操作更改为 UploadFile(),不带参数,ajax 调用进入操作,但是如何恢复发布的数据?

4

2 回答 2

4

好吧,最终这样做了:

服务器端:

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

客户端html:

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

客户端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 表单,也不需要 enctype。 someID 东西由 URL 传递,文件在 Request.Files 中捕获

于 2013-10-28T21:20:11.787 回答
3

如果您想上传文件以及其他一些参数,在您的场景中就是这种情况,HttpPost 处理程序只能有其他参数。然后,您可以从 Request 对象获取发送到服务器的文件。

例如:

[HttpPost]
public ActionResult UploadFile(long someID)
{
    string filename = null;
    string fileType = null;
    byte[] fileContents = null;

    if (Request.Files.Count > 0) { //they're uploading the old way
        var file = Request.Files[0];
        fileContents = new byte[file.ContentLength];
        fileType = file.ContentType;
        filename = file.FileName;
    } else if (Request.ContentLength > 0) {
        fileContents = new byte[Request.ContentLength];
        Request.InputStream.Read(fileContents, 0, Request.ContentLength);
        filename = Request.Headers["X-File-Name"];
        fileType = Request.Headers["X-File-Type"];
    }
    //Now you have the file, continue with processing the POST request 
    //...
}

此示例来自此链接,我发现这对我在 MVC 的第一步非常有帮助。

于 2013-10-28T20:38:17.447 回答