您的位置:首页 > 编程语言 > C#

c# net 简单 上传和下载文件代码

2013-09-29 15:56 417 查看
简单案例 拿来就可以用了

//FileName要下载的文件路径

public static void FileDownload(string FileName)
{
String FullFileName = System.Web.HttpContext.Current.Server.MapPath(FileName);
FileInfo DownloadFile = new FileInfo(FullFileName);
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/octet-stream";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.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();
}
下载,直接调用方法

try
{
if (FileUpload1.PostedFile.FileName.Length == 0)
{
Response.Write("<script>alert(\"上传路径不能为空!\");</script>");
return;
}
string filename = this.FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.LastIndexOf("\\") + 1);
string houzhui = FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.LastIndexOf(".") + 1);
if (houzhui == "gif" || houzhui == "jpg" || houzhui == "bmp")
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("image/" + filename));
Response.Write("<script>alert(\"上传文件成功!\");</script>");
}
else
{
Response.Write("<script>alert(\"上传文件必须是gif,jpg,bmp格式!\");</script>");
return;
}
}
catch (Exception ex)
{
Response.Write("<script>alert(\"" + ex.Message + "\");</script>");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: