2017-08-31 26 views
0

我試圖找到與HTML/JavaScript的/ C#代碼一個很好的例子就只上傳一個文件到服務器上把它保存在服務器上的目錄提供指導。我的代碼給我我的變量,'文件',當我調試它爲空。道場文件上載C#MVC.NET HttpPost沒有上傳

HTML表單:

<form id="uploadForm" method="post" data-dojo-type="dijit/form/Form" enctype="multipart/form-data"> 
    <input 
     id="fileUploadInput" 
     type="file" 
     name="fileUploadInput" 
    > 
    <br /> 
    <br /> 
    <button 
     id="fileUploadButton" 
     data-dojo-attach-point="fileUploadButton" 
     onClick="click" 
    > 
    Upload 
    </button> 
</form> 

道場/ JavaScript代碼:

ioIframe.send({ 
    url: this.proxyPostFile, 
    form: "uploadForm", 
    method: "POST", 
    handleAs: "text", 
    // Callback on successful data call: 
    load: function (response, ioArgs) { 
     return response; 
    }, 
    // Callback on errors 
    error: function (response, ioArgs) { 
     console.info(response) 
    } 
}); 

C#代碼:

[HttpPost] 
public JsonResult Upload(HttpPostedFileBase file) 
{ 
    JsonResult FileData = null; 
    if (Request != null) 
    { 
     try 
     { 
      if (file!=null && file.ContentLength > 0) 
      { 
       ... do some stuff with the file 
      } 
     } 
     catch (Exception ex) 
     { 
      Dictionary<string,string> error = new Dictionary<string,string>(); 
      error.Add("error", "ERROR:" + ex.Message.ToString()); 
      FileData = Json(error); 
     } 
    } 
    else 
    { 
     Dictionary<string,string> callResponse = new Dictionary<string,string>(); 
     callResponse.Add("filename", "You have not specified a file."); 
     FileData = Json(callResponse); 
    } 
    return FileData; 
} 

任何想法或幫助將不勝感激。

謝謝

+0

您的文件輸入具有'name =「fileUploadInput」',它與方法('file')中的參數名稱不匹配。他們需要匹配。但事實上,你返回一個'JsonResult'表明你想要使用Ajax,在這種情況下,請參考[這個答案](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of -model到FORMDATA和-獲得-IT-在-MVC/29293681#29293681) - 你需要使用'FormData'並設置正確的AJAX選項 –

+0

@StephenMuecke這會工作,如果我可以使用jQuery的,但不幸的是我正在使用Dojo。不過謝謝。 –

+0

這並不改變的事實,你的'name'屬性和方法的參數不匹配 - 他們需要:) –

回答

0

你生成的文件輸入與name="fileUploadInput"但你在POST方法的參數被命名爲file文件 - 他們需要以匹配在POST方法中的參數綁定到的形式的控制值。

改變輸入以匹配參數

<input name="file" ... /> 
+0

非常感謝Stephen。這做到了。 –

0

對不起,我有點迷茫,我不知道,如果你想上傳用ajax或格式的文件。如果您正在使用表單,請嘗試將enctype="multipart/form-data"屬性。希望這可以幫助。

+0

很棒的建議。我希望它能夠工作,因爲我相信它確實需要在那裏,但是我添加它後仍然是空的。我將編輯我的帖子。 –

0

看看這個小提琴鏈接。 Dojo提供開箱即用的功能來上傳文件(S)到服務器端(你可以通過URL像/test.php

http://jsfiddle.net/kolban/e47YU/ 

如果你不想通過服務器的URL,或者如果你沒有一個,那麼你需要手動上傳使用dijit.byId("uploader').upload();

+0

@ Manjunatha Muniyappa我很欣賞的反應,但我需要它,而無需使用DojoX中的/上傳 –

+0

你的問題的主題是道場文件上傳,所以我給了這個答案。對不起,如果這對你沒有幫助。 –

+0

沒問題。我正在使用Dojo的其餘部分,但不使用任何Dojox實用程序。不過謝謝。 –