文件的上传与下载
不管是上传也好,下载也好,都需要得到文件的路径
所以,在介绍文件的上传也下载之前,首先还得了解如何操作文件路径
* 传入参数: _FullName = @"C:Temp emp.txt";
*/
/**/ /// <summary>
/// 得到没有后缀的文件名
/// </summary>
/// <param name="_FullName"></param>
/// <returns></returns>
public static string GetFileName( string _FullName)
... {
return Path.GetFileNameWithoutExtension(_FullName);
}
// ---------------------------------->
// 返回值: temp
// 这里不会返回文件的后缀
// 如果传入的文件名是temp.temp.txt方法将返回temp.temp
// ---------------------------------->
/**/ /// <summary>
/// 得到文件扩展名
/// </summary>
/// <param name="_FullName"></param>
/// <returns></returns>
public static string GetExtension( string _FullName)
... {
return Path.GetExtension(_FullName);
}
// ---------------------------------->
// 返回值: .txt
// 这里值得注意的是它返回时将"."包含进去了
// ---------------------------------->
/**/ /// <summary>
/// 得到文件名
/// </summary>
/// <param name="_FullName"></param>
/// <returns></returns>
public static string GetFileName( string _FullName)
... {
return Path.GetFileName(_FullName);
}
// ---------------------------------->
// 返回值: temp.txt
// 文件名 + . + 后缀
// ---------------------------------->
文件的上传于下载
* 传入参数: _DevicePath = @"C:Temp";
* _FileUpload = [System.Web.UI.WebControls.FileUpload];
* out _NewFileName = null;
*/
/**/ /// <summary>
/// 上传文件
/// </summary>
/// <param name="_DevicePath">需要保存到的根路径</param>
/// <param name="_FileUpload">文件上传控件</param>
/// <param name="_NewFileName">返回一个生成后的文件名</param>
/// <returns></returns>
public static bool UpLoadFile( string _DevicePath, System.Web.UI.WebControls.FileUpload _FileUpload, out string _NewFileName)
... {
_NewFileName = String.Empty;
StringBuilder sbPath = new StringBuilder();
sbPath.Append(_DevicePath);
// 检查目录是否存在
if (!Directory.Exists(sbPath.ToString()))
...{
try
...{
// 如果不存在就创建目录
Directory.CreateDirectory(sbPath.ToString());
}
catch (System.Exception ex)
...{
return false;
}
}
string FullName = _FileUpload.PostedFile.FileName; // 得到上传文件全路径
string FileExtension = FileUtil.GetExtension(FullName); // 得到扩展名
// 随机生成文件名
Random random = new Random(DateTime.Now.Millisecond);
string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + random.Next(int.MaxValue).ToString();
_NewFileName = FileName;
sbPath.Append(FileName); // 增加随机生成后的文件名
sbPath.Append(FileExtension); // 加上后缀名
try
...{
// 上传到指定文件夹
_FileUpload.PostedFile.SaveAs(sbPath.ToString());
}
catch (System.Exception ex)
...{
return false;
}
return true;
}
// ---------------------------------->
// 返回值: out _NewFileName 的值是一个随机生成的文件名 yyyyMMddHHmmss + "毫秒数" + "随机数".txt
// ---------------------------------->
/**/ /*
* 传入参数: _DevicePath = @"C:Temp emp.txt";
*/
/**/ /// 下载文件第一种方法
/// <summary>
/// 下载文件
/// </summary>
/// <param name="_Path"></param>
public static void DownloadFileBinary( string _Path)
... {
// 新建一个只读的文件流
System.IO.FileStream fstream = new FileStream(_Path, FileMode.Open);
//设置基本信息
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.AddHeader("Connection", "Keep-Alive");
System.Web.HttpContext.Current.Response.ContentType = "application/x-msdownload";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(_Path));
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fstream.Length.ToString());
while (true)
...{
//开辟缓冲区空间
byte[] buffer = new byte[1024];
//读取文件的数据
int leng = fstream.Read(buffer, 0, 1024);
if (leng == 0)//到文件尾,结束
break;
if (leng == 1024)//读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入
System.Web.HttpContext.Current.Response.BinaryWrite(buffer);
else
...{
//读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块
byte[] b = new byte[leng];
for (int i = 0; i < leng; i++)
b[i] = buffer[i];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
}
}
fstream.Close();//关闭下载文件
System.Web.HttpContext.Current.Response.End();//结束文件下载
}
/**/ /// 下载文件第二种方法
/// <summary>
/// 下载文件
/// </summary>
/// <param name="_Path"></param>
public static void DownloadFile( string _Path)
... {
FileInfo DownloadFile = new FileInfo(_Path);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.ContentType = "application/x-msdownload";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
// ---------------------------------->
// System.Web.HttpContext.Current.Response
// 目的在于:可以使在类中都可以访问Response
// ---------------------------------->
/**/ /*
* 传入参数: _DevicePath = @"C:Temp";
*/
/**/ /// <summary>
/// 删除文件
/// </summary>
/// <param name="_Path"></param>
/// <returns></returns>
public static bool DeleteFile( string _Path)
... {
if (File.Exists(_Path))
...{
try
...{
// 如果文件存在
// 删除文件
File.Delete(_Path);
}
catch (System.Exception ex)
...{
return false;
}
return true;
}
return false;
}
// ---------------------------------->
// 删除文件之前判断文件是否存在
// ---------------------------------->
文件的上传与下载的代码差不多已经可以实现了
以上的代码都可以写在一个单独的类中
在页面中调用此类的"下载文件"方法时有两种实现方式
第一种: FileUtil.DownloadFile(url);这种也是最简单的方法
第二种: 比第一种稍稍麻烦一些,需要修改文件的上传下载类
1) 使此类继承IHttpHandler接口
2) 实现IHttpHandler接口的方法:
/// 使得此类被http访问的入口
/// </summary>
/// <param name="context">提供对用于为 HTTP 请求提供服务的内部服务器对象 Request、Response、Session 和 Server</param>
/// <returns></returns>
public void ProcessRequest(HttpContext context)
... {
string Path = context.Server.UrlDecode(context.Request.QueryString["path"]);
FileUtil.DownloadFileBinary(Path);
}
public bool IsReusable
... {
get ...{ return true; }
}
配置web.config
< system .web >
< httpHandlers >
< add verb ="*" path ="delete.aspx"
type ="命名空间 + 类名, 程序域" />
</ httpHandlers >
</ system.web >
</ configuration >
调用方法
附加: 本人试了很多次用showModalDialog弹出的页面中好像不能使用下载功能
var __value = window.showModalDialog('Default.aspx','window','dialogwidth:450px; dialogheight:450px; center: 1; status: 0; help: 0; scroll: 0; resizable: 0;');
alert(__value);
后来实现是没办法,用window.open来实现弹出页面
window.open('Default.aspx','window','height='+iHeight+',width='+iWidth+',top='+iTop+', left='+iLeft+',toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no');
function(__value){
alert(__value);
}
只不过返回值的时候跟showModalDialog有所不同
// showModalDialog 返回参数方法
window.returnValue = "returnValue";
// window.open 返回参数方法,调用此方法时,将及时更新返回值
window.opener.fileinsert('returnValue');