我需要从服务器向浏览器发送文件(Web客户端)

时间:2014-06-06 14:26:24

标签: c# asp.net

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

//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 个答案:

答案 0 :(得分:0)

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