2011-03-03 35 views
1

此問題主要涉及.net中的Web應用程序中的流。在我的web應用,我將顯示如下:合併流:Web應用程序

  1. bottle.doc
  2. sheet.xls
  3. presentation.ppt
  4. stackof.jpg

    按鈕

我將保留每個人的複選框以供選擇。假設用戶選擇了四個文件並單擊了我保存的按鈕。然後,我爲每種類型的文件實例化分類器,將其轉換爲pdf,我已經寫入並將它們轉換爲pdf並返回它們。我的問題是clases能夠讀取數據表單URL並將它們轉換爲pdf。但我不知道如何返回流併合並它們。

string url = @"url"; 

//Prepare the web page we will be asking for 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
request.ContentType = "application/mspowerpoint"; 
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0"; 

//Execute the request 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

//We will read data via the response stream 
Stream resStream = response.GetResponseStream(); 

//Write content into the MemoryStream 
BinaryReader resReader = new BinaryReader(resStream); 

MemoryStream PresentaionStream = new MemoryStream(resReader.ReadBytes((int)response.ContentLength)); 
//convert the presention stream into pdf and save it to local disk. 

但我想再次返回流。我怎樣才能實現這個任何想法是受歡迎的。

+0

看來你有兩個問題。 1.如何將多個流合併爲一個並將其轉換爲pdf。 2.如何將pdf流返回給客戶端。我會在這裏保留數字2,並提出一個新的問題,因爲它是一個完全不同的主題。 – Peter 2011-03-03 09:22:05

回答

1

我假設這是一個asp.net頁面,並且您從服務中獲取pdf。在將其返回給用戶之前,您不需要將其保存在本地。您只需以塊的形式寫入輸出流即可。

//Execute the request 
HttpWebResponse response = null; 
try 
{ 
    response = (HttpWebResponse)request.GetResponse(); 
} 
catch (WebException we) { // handle web excetpions } 
catch (Exception e) { // handle other exceptions } 

this.Response.ContentType = "application/pdf"; 

const int BUFFER_SIZE = 1024; 
byte[] buffer = new byte[BUFFER_SIZE]; 
int bytes = 0; 
while ((bytes = resStream.Read(buffer, 0, BUFFER_SIZE)) > 0) 
{ 
    //Write the stream directly to the client 
    this.Response.OutputStream.Write(buff, 0, bytes); 
} 
+0

但是在這裏,我用一個請求轉換多個文件。所以我怎麼區分不同的流。 – Tortoise 2011-03-03 09:01:02

+0

那麼我們不能向用戶發送多個響應,所以選項是壓縮它們或讓pdf服務將所有文件合併到一個大pdf中。因此,如果您需要壓縮它們,您需要創建一個zip文件並將該流寫入zip。見http://stackoverflow.com/questions/276319/create-zip-archive-from-multiple-in-memory-files-in-c/276347#276347 – 2011-03-03 10:01:28

1

如果我正確理解你的問題,你可以立即發送響應,這樣用戶將得到一個下載請求。

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 
response.Clear(); 
response.AddHeader("Content-Type", "binary/octet-stream"); 
response.AddHeader("Content-Disposition", "attachment; filename=nameofthefile.pdf; size=" + downloadBytes.Length.ToString()); 
response.Flush(); 
response.BinaryWrite(downloadBytes); 
response.Flush(); 
response.End(); 

其中downloadBytes是byte[]幷包含pdf。

+0

我不想下載,我想將文件直接發送到客戶端的打印機 – Tortoise 2011-03-03 09:01:58

+0

在一個不可能的網絡環境中。你怎麼知道用戶是否有打印機?用我的答案,用戶將收到pdf的下載請求,如果他在下載後打開文件,他可以從他的pdf查看器打印它。 – Peter 2011-03-03 09:18:31

+0

沒有我的應用要求是當用戶應該直接提示打印對話而沒有任何中間步驟。這是我的要求,我正在做一個打印應用程序。 – Tortoise 2011-03-03 09:33:43