2013-10-28 28 views
0

這裏有什麼問題?
Ajax調用沒有達到動作在ASP.net中捕獲ajax文件上傳(html5)MVC

服務器端:

[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調用進入操作,但是如何恢復發佈的數據?

+0

這是一個安全問題,也http://stackoverflow.com/questions/19267749/null-parameter-using-ajax-見beginform-iso-html-beginform – Gerard

+0

這不是安全問題 – sports

回答

3

好,落得這樣做的:

服務器端:

[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逮住

+1

工作正常。如果在表單中包含更多的輸入字段,可以使用新的FormData($('#someFormId')[0])'。這從應該發佈的實際表單構造FormData。然後您可以根據本文中的描述修改該表單數據。 –

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 
    //... 
} 

這個樣本是從這個link,我發現在我的MVC的第一步真的很有幫助。