下载文件块
本文关键字:文件 下载 | 更新日期: 2023-09-27 18:15:47
我的问题如下:有一些SOAP web服务允许读取流文件。我需要读取整个文件分成块并传输给用户。所有操作都不应该阻塞UI主线程:用户在保存文件对话框中按下"保存"按钮,并且能够移动到下一页或执行另一个操作。如果您能提供样品溶液,我将不胜感激。请注意,该解决方案应该与IIS 5.1一起工作。
问候,吉米
用ASP下载文件。. NET逐字节地返回到响应页。查看MSDN:
try
{
System.String filename = "C:''downloadJSP''myFile.txt";
// set the http content type to "APPLICATION/OCTET-STREAM
Response.ContentType = "APPLICATION/OCTET-STREAM";
// initialize the http content-disposition header to
// indicate a file attachment with the default filename
// "myFile.txt"
System.String disHeader = "Attachment;
Filename='"myFile.txt'"";
Response.AppendHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
System.IO.FileInfo fileToDownload = new
System.IO.FileInfo(filename);
System.IO.FileStream fileInputStream = new
System.IO.FileStream(fileToDownload.FullName,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
int i;
while ((i = fileInputStream.ReadByte()) != - 1)
{
Response.Write((char)i);
}
fileInputStream.Close();
Response.Flush();
Response.Close();
}
catch (System.Exception e)
// file IO errors
{
SupportClass.WriteStackTrace(e, Console.Error);
}
有一些文章可以帮助你实现和解决错误:
从HTTPS服务器上的byte()下载excel文件
asp.net从FTP下载文件获取byte[]然后保存为file
通过ASP下载远程文件。. NET损坏文件
反应。WriteFile无法下载大文件
ProcessRequest方法form downloader HttpHandler:
public void ProcessRequest(HttpContext context)
{
RequestTarget target = RequestTarget.ParseFromQueryString(context.Request.QueryString);
Guid requestId = new Guid(context.Request.QueryString["requestId"]);
string itemName = HttpUtility.UrlDecode(context.Request.QueryString["itemName"]);
if (target != null &&
!requestId.Equals(Guid.Empty) &&
!string.IsNullOrEmpty(itemName))
{
HttpResponse response = context.Response;
response.Buffer = false;
response.Clear();
response.AddHeader("Content-Disposition", "attachment;filename='"" + itemName + "'"");
response.ContentType = "application/octet-stream";
int length = 100000, i = 0;
byte[] fileBytes;
do
{
fileBytes = WS.ReadFile(requestId, target, i * length, length);
i++;
response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
response.Flush();
}
while (fileBytes != null && fileBytes.Length == length);
}
}
整个问题不在于组织下载操作,而在于满足下载操作不阻塞UI主线程的条件:用户在保存文件对话框中按下"保存"按钮,并能够移动到下一页或执行另一个操作。Niranjan Kala编写的解决方案导致,当文件非常大时,用户无法看到另一个页面,直到下载操作完成。我很感激,但我不是这个意思。
如果我理解正确的话,您是想让浏览器发起对文件的新请求,而不重新加载当前页面。最简单的方法可能是创建一个target="_blank"的链接。像这样的代码应该做:
<a href="http://yourhost/yourdownloadhandler?requestid=blah&itemName=blahblah" target="_blank">Download file</a>
如果您提供的内容类型为application/octet-stream
,大多数浏览器会将文件保存到磁盘。