2016-04-29 56 views
0

我想通過AJAX從文件發送一個字節數組。它總是一個PDF格式。使用輸入文件通過ajax發送字節數組

所以我的JavaScript + jQuery是如下:

function upload() { 
    var file = document.getElementById("inputFile").files[0]; 

    var fr = new FileReader(); 
    fr.onload = function() { 
     var binaryString = this.result; 

     var objUploader = { 
      element: { 
       Name: "example", 
       Document: binaryString 
      } 
     }; 

     $.ajax({ 
      url: "http://localhost/Uploader/ServiceUploader.svc/saveDocument", 
      data: JSON.stringify(objUploader), 
      dataType: "json", 
      type: "POST", 
      contentType: "application/json; charset=uft-8", 
      success: function (data) { 

      }, 
      error: function (xhr, status, error) { 

      } 
     }); 

    }; 

    //reading file 
    fr.readAsArrayBuffer(file); 
} 

在我的WCF服務,我期望得到這個屬性的對象:

[DataContract] 
    public class UploaderElement 
    { 
     [DataMember] 
     public string Name { get; set; } 
     [DataMember] 
     public byte[] Document { get; set; } 
    } 

而我的函數的定義是這樣的。

long saveDocument(UploaderElement element); 

的問題是,binaryString(這是在使用FileReader JS的結果)總是空的,所以在我的WCF我得到的字節我的財產「文檔」空數組。

這是objUploader的外觀時,發送到服務,如:

{"element":{"Name":"example","Document":{}}} 

我怎樣才能解決這個問題。有沒有更好的方法將PDF字節表示發送到我的WCF?謝謝你,對不起我的英文。

回答

0

binaryString將不會爲空,但其序列化爲JSON將只產生一個{}。因此只需發送文件數據作爲八位字節流

$.ajax({ 
    url: "http://localhost/Uploader/ServiceUploader.svc/saveDocument", 
    type: "POST", 
    contentType: "application/octet-stream", 
    data: binaryString, 
    processData: false, 
    success: function (data) { ... } 
    error: function (xhr, status, error) { ... } 
}); 

並且在服務器上只需要字節數組。

+0

非常感謝,但是我得到'413 Request Entity Too Large'。即使我在我的web.config中有: ' – Fertos

+0

@Fentos不是在這些配置中的專家,但是你不能嘗試一個不同的綁定,例如'webHttpBinding' – wero