2016-08-25 44 views
0

我想上傳一個在ASP.NET中使用XMLHttpRequest和FormData的Excel文件,但總是在ASP.NET中將Request.FIles設置爲null,這裏是我的代碼,請幫助我,Request.Files即將到來ASP.NET

function BulkUploadUsers(e){ 
 
    var url = "/BC/Product/Modules/UserManagement/BulkUpload.aspx?action=import"; 
 
    var fd = new FormData(); 
 
    fd.append("ImportWorkOrderExcelFile", document.getElementById('ctl01_ImportFcpFile').files[0]); 
 
    var xhr = new XMLHttpRequest(); 
 
    xhr.open("POST", url, true); 
 
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 
 
    xhr.setRequestHeader('X-CSRF-Token', document.getElementById("_RequestVerificationToken").value); 
 
    xhr.setRequestHeader("Content-Type", "multipart/form-data"); 
 
    xhr.send(fd); 
 
}
<div> 
 
     <input type="file" id="ImportFcpFile" runat="server" onchange="BulkUploadUsers(this)"/>  
 
    </div>

在Asp.net頁面

protected void Page_Load(object sender, EventArgs e) 
    { 
     try 
     { 
       var aa = FindControl("ImportFcpFile"); 
       HttpPostedFile file = Request.Files["ImportUserExcelFile"]; 

     } 
     catch (Exception ex) 
     { 
     } 
    } 
+0

沒有什麼所謂的'ImportUserExcelFile'在AJAX代碼保存。 – David

+0

使用Request.Files [0]來訪問文件 –

+0

我寧願使用HttpFileCollection fileCollection = HttpContext.Current.Request.Files; –

回答

0

這裏服務器端是我做的

HttpFileCollection fileCollection = HttpContext.Current.Request.Files; 
string savedfile = ""; 
      for (int i = 0; i < fileCollection.Count; i++) 
      { 
       try 
       { 
        HttpPostedFile upload = fileCollection[i]; 
        int f = fileCollection[i].ContentLength; 
        string filename = "/ProductImages/" + fileCollection[i].FileName; 
        upload.SaveAs(Server.MapPath(filename)); 
        savedfile += fileCollection[i].FileName; 
       } 
       catch (Exception ex) 
       { 
        List<string> ff = new List<string>(); 
        ff.Add(ex.Message.ToString()); 
        System.IO.File.WriteAllLines(Server.MapPath("/ProductImages/Error.txt"), ff); 
       } 

      } 

這是我使用的JavaScript代碼。我想你已經錯過了一些東西

 function handleDnDFileSelect(event) { 


      /* Read the list of all the selected files. */ 
      var files = event.dataTransfer.files; 

      /* Consolidate the output element. */ 
      var form = document.getElementById('form1'); 

     var fd= new FormData(form); 

      for (i = 0; i < files.length; i++) { 
       fd.append(files[i].name, files[i]); 
      } 
      var xhr = new XMLHttpRequest(); 
     xhr.onreadystatechange = function() { 
      if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) { 
       alert("upload done!"); 
      } else { 
       //alert("upload failed!"); 
      } 
     }; 
     xhr.open('POST', "/BC/Product/Modules/UserManagement/BulkUpload.aspx"); 
     // xhr.setRequestHeader("Content-type", "multipart/form-data"); 
     xhr.send(fd); 

     } 

我只是通過遍歷文件與任何名義,我想

+0

嗨Mysterio HttpContext.Current.Request.Files爲空 –

+0

仍然它的未來空。 IIS級別需要什麼嗎? –

+0

沒有。你知道jQuery嗎?它更容易使用jQuery –