2014-03-26 69 views
0

我試圖上傳一個圖像而不使用任何asp控件。到目前爲止,我一直在努力:未使用任何Asp控件的文件上傳

 <form id="form1" data-ajax="false" method="post" runat="server" enctype="multipart/form-data"> 
      <input type="file" id="uploadFile" name="uploadFile" runat="server"/> 
      <input type="submit" class="btn-login" data-corners="true" value="Yükle" onclick="UploadPhoto()" /> 
     </form> 
在我的.aspx頁面中

和JQuery的在UploadPhoto()方法:

function UploadPhoto() { 
      $.ajax({ 
       type: "POST", 
       url: "IncidentChange.aspx/UploadPhoto", 
       contentType: "application/json; charset=utf-8", 
       success: function (msg) { 
       }, 
       error: function() { 
       } 
      }); 
     } 

我張貼到C#代碼後面。但是,我無法從代碼隱藏中獲取上傳的內容。

 [WebMethod] 
     public static string UploadPhoto() 
     { 
      try 
      { 
       byte[] fileData = null; 
       using (var binaryReader = new BinaryReader(HttpContext.Current.Request.Files[0].InputStream)) 
       { 
        fileData = binaryReader.ReadBytes(HttpContext.Current.Request.Files[0].ContentLength); 
       } 

      } 
      catch (Exception ex) 
      { 
      } 
      return null; 
     } 

但Request.Files看起來是一個空數組。由於該方法是靜態的([WebMethod]),我無法訪問該方法中的輸入控件以獲取發佈的文件。我怎樣才能克服這個問題?謝謝。

+0

你不發送在阿賈克斯數據 – kobe

回答

2

HTML:

<input type="file" id="uploadFile" name="uploadFile"/> 
<input type="button" id="submit" value="Submit" onClick="UploadFile();"/> 

JQuery的:

<script type="text/javascript"> 
$(document).ready(function() { 
     function UploadFile() { 
    var fileName = $('#uploadFile').val().replace(/.*(\/|\\)/, ''); 
         if (fileName != "") { 
         $.ajaxFileUpload({ url: 'AjaxFileUploader.ashx', 
          secureuri: false, 
          fileElementId: 'uploadFile', 
          dataType: 'json', 
          success: function (data, status) { 
           if (typeof (data.error) != 'undefined') { 
         if (data.error != '') { 
          alert(data.error); 
         } else { 
          alert('Success'); 
         } 
        } 
       }, 
        error: function (data, status, e) { 
           alert(e); 
          } 
         } 
         ) 
        } 
} 
}); 

請從tyhe bekow鏈接下載AJAX文件上傳插件。

http://www.phpletter.com/DOWNLOAD/

處理程序:

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.IO; 
    using System.Text.RegularExpressions; 
    using System.Text; 
namespace MyProject 
{ 
    public class AjaxFileUploader : IHttpHandler 
    { 
    { 

     public void ProcessRequest(HttpContext context) 
     { 

      if (context.Request.Files.Count > 0) 
      { 
       string path = context.Server.MapPath("~/UploadImages"); 
       if (!Directory.Exists(path)) 
        Directory.CreateDirectory(path); 

       var file = context.Request.Files[0]; 

       string fileName; 

       if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") 
       { 
        string[] files = file.FileName.Split(new char[] { '\\' }); 
        fileName = files[files.Length - 1]; 
       } 
       else 
       { 
        fileName = file.FileName; 
       } 
       string newFilename = Guid.NewGuid().ToString(); 
       FileInfo fInfo = new FileInfo(fileName); 
       newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension); 
       string strFileName = newFilename; 
       fileName = Path.Combine(path, newFilename); 
       file.SaveAs(fileName); 


       string msg = "{"; 
       msg += string.Format("error:'{0}',\n", string.Empty); 
       msg += string.Format("msg:'{0}'\n", strFileName); 
       msg += "}"; 
       context.Response.Write(msg); 


      } 
     } 

     public bool IsReusable 
     { 
      get 
      { 
       return true; 
      } 
     } 
    } 
} 
+0

文件我不能讓你的代碼工作。我無法將文件發佈到.ashx –

+0

我已更新我的答案。請檢查。 – RGS

+0

謝謝,我欣賞它,但它仍然不回傳。您確定<%@ WebHandler Language =「C#」Class =「AjaxFileUploader」%>行應該在.ashx.cs文件中嗎?它甚至沒有這樣編譯。 –

0

爲什麼你不使用默認的ASP控制??這是很好的使用由.NET框架work.Using默認提供的默認控件控件將刪除長期運行的任何依賴項。

+0

這是一個HTML5項目,適用於手機。沒有asp標籤,這是客戶的要求。 –

+0

另外,這並沒有任何幫助。如果可以的話,我會降低你的答案。 –

1

是的,你可以通過ajax post方法來實現這一點。在服務器端你可以使用httphandler。

用ajax你也可以顯示上傳進度。

您必須將該文件作爲輸入流讀取。

using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName)) 
    { 
     Byte[] buffer = new Byte[32 * 1024]; 
     int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length); 
     while (read > 0) 
     { 
      fs.Write(buffer, 0, read); 
      read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length); 
     } 
    } 

示例代碼

function sendFile(file) {    
     debugger; 
     $.ajax({ 
      url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data 
      type: 'POST', 
      xhr: function() { 
       myXhr = $.ajaxSettings.xhr(); 
       if (myXhr.upload) { 
        myXhr.upload.addEventListener('progress', progressHandlingFunction, false); 
       } 
       return myXhr; 
      }, 
      success: function (result) {      
       //On success if you want to perform some tasks. 
      }, 
      data: file, 
      cache: false, 
      contentType: false, 
      processData: false 
     }); 
     function progressHandlingFunction(e) { 
      if (e.lengthComputable) { 
       var s = parseInt((e.loaded/e.total) * 100); 
       $("#progress" + currFile).text(s + "%"); 
       $("#progbarWidth" + currFile).width(s + "%"); 
       if (s == 100) { 
        triggerNextFileUpload(); 
       } 
      } 
     } 
    } 
相關問題