getfile.cs

来自「完全网站系统」· CS 代码 · 共 48 行

CS
48
字号
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ASPNET.StarterKit.Communities.Downloads 
{
	/// <summary>
	/// Streams the binary data of a file to the client.
	/// </summary>
	public class GetFile : Control 
	{
		public GetFile() 
		{
			// If there's no ID throw an error
			if (Context.Request.QueryString["ID"] == null)
				throw new ArgumentNullException("No ContentPage ID");
			int contentPageID = Int32.Parse(Context.Request.QueryString["ID"]);
			
			SqlDataReader dr = DownloadsUtility.GetFile(contentPageID);
			if (!dr.Read()) 
			{
				// Nothing to read
				Context.Response.Write("Error: File not found.");
				Context.Response.End();
				return;
			}
			string fileName = dr.GetString(0);
			int fileSize = dr.GetInt32(1);
			Context.Server.ScriptTimeout = 600;
			Context.Response.Buffer=true;
			Context.Response.Clear();
			Context.Response.ContentType="application/octet-stream";
			Context.Response.AddHeader("Content-Disposition","attachment; filename=\"" + fileName + "\";");
			Context.Response.AddHeader("Content-Length",fileSize.ToString());
			byte[] fileBuffer=new byte[fileSize]; // buffer of the file data
			dr.GetBytes(2, 0, fileBuffer, 0, fileSize);
			Context.Response.BinaryWrite(fileBuffer);
			dr.Close();
			// End the response
			Context.Response.End();
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?