2011-03-03 60 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