显示页面Html代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Downloadfile.aspx.cs" Inherits="Downloadfile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:FileUpload ID="FileUpload1" runat="server" />
        
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="提 交" /></div>
    
</form>
</body>
</html>


显示页面CS代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class Downloadfile : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }


    
private void DownloadFile(string physicalFilePath)
    
{
        FileStream stream 
= null;
        
try
        
{
            stream 
= new FileStream(physicalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            
int bufSize = (int)stream.Length;
            
byte[] buf = new byte[bufSize];

            
int bytesRead = stream.Read(buf, 0, bufSize);
            HttpContext.Current.Response.ContentType 
= "application/octet-stream";
            
//attachment是以附件的形式下载,也可以改为online在线找开. 
            HttpContext.Current.Response.AppendHeader("Content-Disposition""online;filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(physicalFilePath), System.Text.Encoding.UTF8));
            HttpContext.Current.Response.OutputStream.Write(buf, 
0, bytesRead);
            HttpContext.Current.Response.End();
        }

        
finally
        
{
            stream.Close();
        }

    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        
if (FileUpload1.HasFile)
        
{
            
string fileload = FileUpload1.PostedFile.FileName;
            DownloadFile(fileload);
        }

        
else
        
{
            Response.Write(
"<script>alert('请先上传文件');</script>");
        }

    }

}
posted on 2007-04-17 10:10  小角色  阅读(205)  评论(0)    收藏  举报