2017-03-22 6 views
0

jQuery ajax呼び出しを使用してWCF RESTサービスからpdfファイルをダウンロードしようとしていますが、エンコードの問題があると思います。WCF REST jqueryでpdfをダウンロードする

はここ

public Stream DownloadFile(RequestDownloadFile fileDownload) 
{ 
     DBCepPortaleEntities cepPortale = CEP.DAL.DbConnections.GetConnessionePortale(ConnString); //connection with entity framework to SQLServer DB 

     var cerco = from cc in cepPortale.WEB_DOCUMENTI 
        where cc.IdDocumento == fileDownload.ID 
        select cc; //retrieving a Pdf VARBINARY Field 
     if (cerco.Count() > 0) 
     { 



      WEB_DOCUMENTI doc = cerco.First(); 


      String nomeFile = @"test.pdf"; 
      String tmp = Encoding.Default.GetString(doc.DocPDF); 
      File.WriteAllText(nomeFile, tmp, Encoding.Default);//test: pdf file is written correctly and I can read it 
      WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; 
      WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=circolare" + fileDownload.ID + ".pdf"); 
      WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Transfer-Encoding", "binary"); 
      WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Encoding", "none"); 

      FileStream f = new FileStream(nomeFile, FileMode.Open); 
      int length = (int)f.Length; 
      WebOperationContext.Current.OutgoingResponse.ContentLength = length; 
      byte[] buffer = new byte[length]; 
      int sum = 0; 
      int count; 
      while ((count = f.Read(buffer, sum, length - sum)) > 0) 
      { 
       sum += count; 
      } 
      f.Close(); 
      return new MemoryStream(buffer); 
     } 
     else 
      return null; 
} 

このメソッドは、正しく "test.pdfという" と呼ばれるPDFファイルを作成し、サービスインターフェイスメソッドの定義

[OperationContract] 
    [WebInvoke(
     BodyStyle = WebMessageBodyStyle.Bare, 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, 
     Method="POST", 
     UriTemplate = "DownloadFile")] 
    Stream DownloadFile(RequestDownloadFile fileDownload); 

、その後の実装です。

今私はAJAX呼び出しでそれを消費しようとしている:

$.ajax({ 
        method: "POST", 
        url: "http://testwcfcircolari.bresciapaghe.it/Service.svc/DownloadFile", 
        data: '{"Token":"abc", "ID":"20"}', 
        contentType: "application/json", 
        success: function (response, status, xhr) { 
         console.log(response); 
         //self.settings.onSuccessStart(response, status, xhr, self); 

         // Check if a filename is existing on the response headers. 
         var filename = ""; 
         var disposition = xhr.getResponseHeader("Content-Disposition"); 
         if (disposition && disposition.indexOf("attachment") !== -1) { 
          var filenameRegex = /filename[^;=\n]*=(([""]).*?\2|[^;\n]*)/; 
          var matches = filenameRegex.exec(disposition); 
          if (matches != null && matches[1]) 
           filename = matches[1].replace(/[""]/g, ""); 
         } 

         filename = "prova.pdf"; 


         var type = xhr.getResponseHeader("Content-Type"); 
         var blob = new Blob([response], { type: "application/pdf; charset=UTF-8" }); 

         if (typeof window.navigator.msSaveBlob !== "undefined") { 
          // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed. 
          window.navigator.msSaveBlob(blob, filename); 
         } else { 
          var URL = window.URL || window.webkitURL; 
          var downloadUrl = URL.createObjectURL(blob); 
          alert(filename); 
          if (filename) { 
           // Use HTML5 a[download] attribute to specify filename. 
           var a = document.createElement("a"); 
           // Safari doesn"t support this yet. 
           if (typeof a.download === "undefined") { 
            window.location = downloadUrl; 
           } else { 
            a.href = downloadUrl; 
            a.download = filename; 
            document.body.appendChild(a); 
            a.click(); 
           } 
          } else { 
           window.location = downloadUrl; 
          } 
          //console.log(downloadUrl); 
          setTimeout(function() { 
           URL.revokeObjectURL(downloadUrl); 
          }, 100); // Cleanup 
         } 
         // Final custom event. 
         //self.settings.onSuccessFinish(response, status, xhr, self, filename); 
        }, 
        error: function (XMLHttpRequest, textStatus, errorThrown) { 
         alert('Error occurred while opening fax template' + XMLHttpRequest + " " + 
           +textStatus + " " + errorThrown); 
        } 
       }); 

結果は、元の同じページを持つPDFファイルですが、内容はすべて空白になっています。 ダウンロードしたpdfのテキストエディタの内容を見ると、スターターファイルとは異なります。

提案がありますか? ありがとうございます。

答えて

0

C#

String[] filename=filepath.Split('\\');    
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream"; 
if(File.Exists(filepath) 
{ 
    String header = "attachment; filename=" + filename[filename.Length - 1]; 
    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = header; 
    return File.OpenRead(filepath); 
} 

JS

function downloadfile(filepath) 
{  
var url="https://myfile.ololo?v="+filepath; 
window.open(url,"windowname","width:400,height:300"); 
} 

<bindings> 
    <webHttpBinding> 
    <binding name="MyWcfRestService.WebHttp" maxBufferSize="2147483637" 
      maxBufferPoolSize="2147483637" 
      maxReceivedMessageSize="2147483637" 
      transferMode="Streamed" 
      sendTimeout="00:05:00"> 
     <readerQuotas maxDepth="2147483637" 
        maxStringContentLength="2147483637" 
        maxArrayLength="2147483647" 
        maxBytesPerRead="2147483647" 
        maxNameTableCharCount="2147483637"/> 
     <security mode="None" /> 
    </binding> 
    </webHttpBinding> 
</bindings> 
+0

を結合ありがとうございました。 –

+0

ありがとうございました!このように私はGETメソッドを使用してファイルを取得しますが、クライアントが決定されたファイルにアクセスする権限を持っていることを確認するためにトークンを渡す必要があります。それを行う方法はありますか? –