2015-04-22 48 views
0

我想使用AJAX上傳文件問題是我是.net中的新手,不知道我是否做得對或不對,所以我非常感謝任何幫助或建議。如何在AJAX上調用fileupload中的.net方法更改?

這裏是我的html代碼:

<asp:FileUpload ID="FileUpload1" onChange="Show()" runat="server" /> 

我的方法應該當用戶選擇其文件

這是我在MSDN中發現的腳本中調用:

<script type="text/javascript"> 
    function Show() { 
     var file = document.getElementById("FileUpload1"); 
     alert("test") 
     $.ajax({ 
      type: "POST", 
      url: "SendSms.aspx/StaticUpdate", 
      data: '{name:"test" }', 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: OnSuccess, 
      failure: function (response) { 
       alert("test1"); 
      } 
     }); 
    } 
    function OnSuccess(response) { 
     alert("test2"); 
    } 
</script> 

,這裏是我的ASP方法:

[System.Web.Services.WebMethod] 
public static void StaticUpdate() 
{ 
    SendSms upload = new SendSms(); 
    upload.Upload(); 
} 

public void Upload() 
{ 
    string FileName = System.DateTime.Now.ToString("ddmmyyhhmmsss") + FileUpload1.FileName; 
    if (IsPostBack) 
    { 
     Boolean fileOK = false; 
     String path = Server.MapPath("~/Upload/"); 
     if (FileUpload1.HasFile) 
     { 
      String fileExtension = 
       System.IO.Path.GetExtension(FileName).ToLower(); 
      String[] allowedExtensions = { ".txt" }; 
      for (int i = 0; i < allowedExtensions.Length; i++) 
      { 
       if (fileExtension == allowedExtensions[i]) 
       { 
        fileOK = true; 
       } 
      } 
     } 
     if (fileOK) 
     { 
      try 
      { 
       FileUpload1.PostedFile.SaveAs(path 
        + FileName); 
       System.IO.StreamReader myFile = 
new System.IO.StreamReader("C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName + ""); 
       TextBox2.Text = myFile.ReadToEnd(); 
       myFile.Close(); 
       string Path = "C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName + ""; 
       System.IO.File.Delete(Path); 
      } 
      catch (Exception ex) 
      { 
       Label1.Text = "File could not be uploaded."; 
      } 
     } 
     else 
     { 
      Label1.Text = "Cannot accept files of this type."; 
     } 
    } 

} 

我得到的錯誤是這樣的:

NullReferenceException未被用戶代碼處理。 未將對象引用設置爲對象的實例。

在此先感謝

+1

在你的方法設置一個斷點,並通過它一步,當它被調用。您正在使用的對象之一可能未正確初始化。 (並且這個錯誤是說它可能是其中的任何一個)點擊左邊的行號來打開一個斷點,然後在執行時使用F10來遍歷它。 – Tim

+0

錯字? 'onchange =「ShowCurrentTim()」' – Jasen

+0

@Tim它不是問題 – user1435897

回答

0
string filename = System.IO.Path.GetFileName(FileUpload1.FileName); 
string ext = System.IO.Path.GetExtension(FileUpload1.FileName); 
if (fileExtension == ".txt"){ 

      using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(("C:\\inetpub\\wwwroot\\Viber_Bulk_UI\\Upload\\" + FileName), System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read, 8, System.IO.FileOptions.None)) 
     { 
      byte[] data = System.Text.Encoding.ASCII.GetBytes(FileName); 
      fs.Write(data, 0, data.Length); 
      fs.Flush(); 
      fs.Close(); 
     } 
    } 
相關問題