2014-06-06 106 views
0

我需要从服务器发送文件到浏览器(Web客户端)C#(ASP.NET) 但同时下载文件时,程序继续执行。 我尝试使用任务,线程异步方法...我需要从服务器发送文件到浏览器(Web客户端)

//Create a WebRequest to get the file 
FileWebRequest fileReq = (FileWebRequest)FileWebRequest.Create(this.CaminhoCompleto); 

//Create a response for this request 
FileWebResponse fileResp = (FileWebResponse)fileReq.GetResponse(); 

if (fileReq.ContentLength > 0) 
fileResp.ContentLength = fileReq.ContentLength; 

//Get the Stream returned from the response 
stream = fileResp.GetResponseStream(); 


// prepare the response to the client. resp is the client Response 
HttpResponse resp = HttpContext.Current.Response; 

//ERRO!!! 
teste(stream, resp, fileResp); 

string nomeArq = fileResp.ResponseUri.Segments[(fileResp.ResponseUri.Segments.Length) - 1]; 

//Indicate the type of data being sent 
resp.ContentType = "application/octet-stream"; 

//Name the file 
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + nomeArq + "\""); 
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString()); 

//await stream.CopyToAsync(resp.OutputStream); 
+1

该文件是在当你的控制器执行完毕......如果处理不响应的重要这是只有发送的HttpResponse返回,你就可以开始一个新的线程不会阻止响应的发送。 – Bun

+0

为什么使用FileWebRequest而不是普通的FileStream? –

+0

我想用这个[代码](http://codes.codedigest.com/CodeDigest/39-File-Download-in-ASP-Net-with-C-.aspx)异步 –

回答

0

使用iframe从服务器请求的文件。您可以使用JavaScript创建一个,并将其src作为服务器端点。当内容准备好下载时,它将从浏览器打开保存对话框。

相关问题