- 论坛徽章:
- 0
|
/*********************
FTP Download and Upload
by netbor
*********************/
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;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
public partial class Ftp : System.Web.UI.Page
{
BaseClass bc = new BaseClass();
static string path;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//打开要下载的文件
string str = this.FileUpload1.PostedFile.FileName;
string ss = str.Substring(str.LastIndexOf("\\" + 1);
string s = Server.MapPath("./" + ss);
path = "ftpfiles\\" + ss;
string filepath = GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text.ToString();
string Npath = s + filepath;
System.IO.FileStream r = new System.IO.FileStream(Npath, System.IO.FileMode.Open);
//设置基本信息
Response.Buffer = false;
Response.AddHeader("Connection", "Keep-Alive" ;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(Npath), Encoding.UTF );
Response.AddHeader("Content-Length", r.Length.ToString());
while (true)
{
//开辟缓冲区空间
byte[] buffer = new byte[1024];
//读取文件的数据
int leng = r.Read(buffer, 0, 1024);
if (leng == 0)//到文件尾,结束
break;
if (leng == 1024)//读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入
Response.BinaryWrite(buffer);
else
{
//读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块
byte[] b = new byte[leng];
for (int i = 0; i < leng; i++)
b = buffer;
Response.BinaryWrite(b);
}
}
r.Close();//关闭下载文件
Response.End();//结束文件下载
}
catch (Exception)
{
Response.Write(bc.MessageBox("操作失败!文件已被删除!" );
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string str = this.FileUpload1.PostedFile.FileName;
if (str == ""
{
Response.Write(bc.MessageBox("请选择上传文件!" );
return;
}
string ss = str.Substring(str.LastIndexOf("\\" + 1);
string s = Server.MapPath("ftpfiles\\" + ss);
path = "ftpfiles\\" + ss;
if (File.Exists(s))
{
Response.Write(bc.MessageBox("该文件已经存在,请重新命名!!!" );
return;
}
this.FileUpload1.PostedFile.SaveAs(s);
string lenth = str.Length.ToString();
string ch;
ch = "insert into ftp values('" + ss + "','" + path + "','" + lenth + "','" + DateTime.Now + "','" + Session["loginName"] + "')";
Boolean bl;
bl = bc.ExecSQL(ch);
if (bl)
{
Response.Write(bc.MessageBox("上传成功!" );
Response.Write("<meta http-equiv=refresh content=0/>" ;
}
else
{
Response.Write(bc.MessageBox("上传失败" );
}
}
catch (Exception)
{
Response.Write(bc.MessageBox("数据库连接失败!请检查网络!"));
}
}
protected void Button3_Click(object sender, EventArgs e)
{
}
} |
|