木子屋 Dnawo's BLOG

弹出保存窗口下载服务器上的任何文件[未知大小]

👤 dnawo 📅 2007-08-31 👁 4878 👍 0 💬 0 🔄 源码之家
在IE进行文档链接时,如果遇到OLE支持的文档,IE会自动调用相应程序打开它,有时候这种功能并不是我们所需的,虽然我们可以提醒用户用鼠标右键-->"目标另存为...."命令来下载文档,但这样毕竟不太友好,本文描述了利用FSO及Stream方法实现IE直接下载文档。主程序代码如下:

<%
Sub SaveFile(sFile)
	Dim sPath,objTs,objFso,F
	sPath = Server.MapPath(sFile)    
	Response.Buffer = True    
	Response.Clear    
	Set objTs = Server.CreateObject("ADODB.Stream")    
	objTs.Open    
	objTs.Type = 1    
	On  Error  Resume  Next    
	Set objFso = Server.CreateObject("Scripting.FileSystemObject")
	If Not objFso.FileExists(sPath) Then 
		Response.Write("<h1>Error:</h1>"&sPath&"你要下载的文件不存在!<p>")    
		Response.End    
	End  If

	
	Set objFile = objFso.GetFile(sPath)    
	objTs.LoadFromFile(sPath)
	If Err Then    
		Response.Write("<h1>Error: </h1>Unknown Error!<p>")    
		Response.End 
	End If  
	
	Response.AddHeader "Content-Disposition","attachment;filename="&objFile.name    
	Response.AddHeader "Content-Length",objFile.Size    
	Response.CharSet = "GB2312"    
	Response.ContentType = "application/octet-stream"    
	Response.BinaryWrite  objTs.Read    
	Response.Flush        
	objTs.Close    
	Set objTs = Nothing
End Sub

Call SaveFile("test.asp")
%>

C#版:

<%@ WebHandler Language="C#" Class="Download" %>

using System;
using System.Web;
using System.IO;

public class Download : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        byte[] buffer;
        FileInfo file = new FileInfo(context.Server.MapPath("/rp Source.rar"));

        using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
        {
            buffer = new byte[fs.Length];
            fs.Read(buffer, 0, (int)fs.Length);
        }

        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", "attachment;FileName=" + file.Name);
        context.Response.AddHeader("Content-Length", file.Length.ToString());
        context.Response.BinaryWrite(buffer);
        context.Response.End();
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ASP中的常用服务器检测源码 下一篇 → 让IT工作者过劳的13个坏习惯