2014-10-31 143 views
3

我正在編寫一個C#ASP.Net MVC應用程序,以便客戶端將文件發佈到其他服務器。我使用通用處理程序來處理從客戶端到服務器的發佈文件。但在我的處理程序中,System.Web.HttpContext.Current.Request.Files始終爲空(0計數)。Request.Files始終爲空

表格代號:

@model ITDB102.Models.UploadFileResultsModels 
@{ 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<div> 
    <h1>Upload File</h1> 
    <form id="file-form" action="/Files/UploadFile" method="post" data-ajax="false" enctype="multipart/form-data"> 
     <div><input type="file" id="FilePath" name="FilePath"/> 
     <button type="submit">Send File</button></div> 
    </form> 
</div> 

@section scripts{ 
    <script src="~/Scripts/jquery-1.10.2.js"></script> 
    <script type="text/javascript"> 

     // Variable to store your files 
     var files; 
     var form = document.getElementById('file-form'); 

     // Add events 
     $('input[type=file]').on('change', prepareUpload); 

     // Grab the files and set them to our variable 
     function prepareUpload(event) { 
      files = $('#FilePath').get(0).files; 
     } 

     form.onsubmit = function (event) { 
      uploadFiles(event); 
     } 

     // Catch the form submit and upload the files 
     function uploadFiles(event) { 
      event.stopPropagation(); // Stop stuff happening 
      event.preventDefault(); // Totally stop stuff happening   

      // Create a formdata object and add the files 
      var data = new FormData(); 
      if (files.lenght > 0) 
      { 
       data.append('UploadedFiles', files[0], file[0].name); 
      } 

      //setup request 
      var xhr = new XMLHttpRequest(); 
      //open connection 
      xhr.open('POST', '/Files/UploadFile',false); 
      xhr.setRequestHeader("Content-Type", files.type); 
      //send request 
      xhr.send(data); 

     } 

    </script> 

} 

處理程序:

/// <summary> 
    /// Uploads the file. 
    /// </summary> 
    /// <returns></returns> 
    [HttpPost] 
    public virtual ActionResult UploadFile() 
    { 
     HttpPostedFile myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; 

     bool isUploaded = false; 
     string message = "File upload failed"; 

     if (myFile != null && myFile.ContentLength != 0) 
     { 
      string pathForSaving = Server.MapPath("~/Uploads"); 
      if (this.CreateFolderIfNeeded(pathForSaving)) 
      { 
       try 
       { 
        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName)); 
        isUploaded = true; 
        message = "File uploaded successfully!"; 
       } 
       catch (Exception ex) 
       { 
        message = string.Format("File upload failed: {0}", ex.Message); 
       } 
      } 
     } 
     return Json(new { isUploaded = isUploaded, message = message }, "text/html"); 
    } 


    #region Private Methods 

    /// <summary> 
    /// Creates the folder if needed. 
    /// </summary> 
    /// <param name="path">The path.</param> 
    /// <returns></returns> 
    private bool CreateFolderIfNeeded(string path) 
    { 
     bool result = true; 
     if (!Directory.Exists(path)) 
     { 
      try 
      { 
       Directory.CreateDirectory(path); 
      } 
      catch (Exception) 
      { 
       /*TODO: You must process this exception.*/ 
       result = false; 
      } 
     } 
     return result; 
    } 

    #endregion 

請幫助我。謝謝。

回答

3

最後,我發現了這個問題。

在我的控制器中的代碼var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"];從來沒有工作出於某種原因。我的ajax沒有任何問題。 我改變了我的代碼在控制器中的波紋管,它現在正在工作。

[HttpPost] 
    public virtual ActionResult UploadFile() 
    { 
     //var myFile = System.Web.HttpContext.Current.Request.Files["UploadedFiles"]; 
     // 
     bool isUploaded = false; 
     string message = "File upload failed"; 

     for (int i = 0; i < Request.Files.Count; i++) 
     { 
      var myFile = Request.Files[i]; 

      if (myFile != null && myFile.ContentLength != 0) 
      { 
       string pathForSaving = Server.MapPath("~/Uploads"); 
       if (this.CreateFolderIfNeeded(pathForSaving)) 
       { 
        try 
        { 
         myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName)); 
         isUploaded = true; 
         message = "File uploaded successfully!"; 
        } 
        catch (Exception ex) 
        { 
         message = string.Format("File upload failed: {0}", ex.Message); 
        } 
       } 
      } 

     } 


     return Json(new { isUploaded = isUploaded, message = message }, "text/html"); 
    } 

    #endregion 

    #region Private Methods 

    /// <summary> 
    /// Creates the folder if needed. 
    /// </summary> 
    /// <param name="path">The path.</param> 
    /// <returns></returns> 
    private bool CreateFolderIfNeeded(string path) 
    { 
     bool result = true; 
     if (!Directory.Exists(path)) 
     { 
      try 
      { 
       Directory.CreateDirectory(path); 
      } 
      catch (Exception) 
      { 
       /*TODO: You must process this exception.*/ 
       result = false; 
      } 
     } 
     return result; 
    } 

    #endregion 

} 
-1

要發佈文件,發佈數據必須採用multipart/form-data編碼類型。所以你必須設置請求頭如下:

xhr.setRequestHeader(「Content-Type」,「multipart/form-data」);

請參閱樣本:Upload File With Ajax XmlHttpRequest

+0

試過了,它仍然沒有工作。在我的表單頭部旁邊已經包含了代碼<... enctype =「multipart/form-data」>。 – BNguyen 2014-11-03 19:04:57

1

您需要設置以下爲xhr

dataType: 'json', 
contentType: false, 
processData: false, 

參見幫助鏈接 - File upload using MVC 4 with Ajax

我看到,你已經包括jquery庫和使用jquery選擇,那麼你爲什麼不使用$.ajaxPOST要求?如果您對jquery感興趣,以下是腳本。

$.ajax({ 
    type: "POST", 
    url: '/Files/UploadFile', 
    data: data, 
    dataType: 'json', 
    contentType: false, 
    processData: false, 
    success: function(response) { 
    alert('succes!!'); 
    }, 
    error: function(param1,param2,param3) { 
    alert("errror"); 
    } 
}); 
+0

我在一開始就使用了ajax版本,並沒有奏效。 – BNguyen 2014-11-03 19:07:29