asp.net 上传和下载这2天天天看到 下面我贴写自己的代码

hebaobao19880921 2011-08-04 05:01:13
我刚转Web不久,做了一个资源管理系统 也涉及到了上传下载.下面贴下代码给新手看看.高手给点意见 提供一些地址给我们新人.写的错误的地方请见谅.

首先是上传,这里借鉴的是孟子E章前辈的,然后自己修改了一下.上传到数据库和服务器指定文件夹
上传.百度搜孟子E章多文件上传就可以了 这是我后台的函数

//上传文件
public void FN_UpFiles()
{
//遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
//StringBuilder strMsg = new StringBuilder();
//strMsg.Append("上传的文件分别是:<hr color='pink'/>");
try
{
for (int iFile = 0 ; iFile < files.Count ; iFile++)
{
//检查文件扩展名字
HttpPostedFile postedFile = files[iFile];
string fileName = "";
//string fileExtension = "";
fileName = Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
try
{
string strpath = HttpContext.Current.Request.MapPath("~/ResourcesFolder/") + fileName;
if (System.IO.File.Exists(strpath))
{
Response.Write("已经存在文件:" + fileName + "<br>");
}
else
{
try
{
NRModel.File model = new NRModel.File();
NRBLL.File bf = new NRBLL.File();
Guid guid1 = Guid.NewGuid();
Guid guid2 = Guid.NewGuid();
Guid guid3 = Guid.NewGuid();
Guid guid4 = Guid.NewGuid();
model.Fileid = guid1;
model.Folderid = guid2;
model.Filepath = strpath;
model.FileNam = fileName.ToString();
model.FileSize = postedFile.ContentLength;
model.Decription = this.decrition.Value;
model.CreateOn = DateTime.Now;
model.CreateBy = guid3;
model.ModefyBy = guid4;
if (bf.FN_AddNewRes(model) > 0)
{
//fileExtension = Path.GetExtension(fileName);
//strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
//strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");
//strMsg.Append("上传文件的文件名:" + fileName + "<br>");
//strMsg.Append("上传文件的扩展名:" + fileExtension + "<br>");
//strMsg.Append("上传文件的大小:" + postedFile.ContentLength.ToString() + "个字节" + "<br>");
postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/ResourcesFolder/") + fileName);
Page.RegisterStartupScript("提示", "<script language='javascript'>alert('上传成功!')</script>");
Response.Write("<script language='javascript'>self.opener.location.reload();</script>");
Response.Write("<script language='javascript'>window.close();</script>");
}
}
catch (Exception ex)
{

Response.Write(ex.ToString());
}

}

}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
else
{
Page.RegisterStartupScript("提示", "<script language='javascript'>alert('没有添加上传文件!')</script>");
}
}
//strStatus.Text = strMsg.ToString();
}
catch (System.Exception ex)
{
Response.Write(ex.ToString());
}
}

下载我一共写了几种方式 其实网站都有 积累一下

#region 二进制下载
private void FN_ResponseFile()
{
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
string id = Request["id"].ToString();//获取资源的编号
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if (bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null)//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径
string filename = System.IO.Path.GetFileName(filepath);//获取资源名称

try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(filename));//解码(注意这里2层解码)
filename = filename.Replace("+", "%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length); Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception)
{
Response.Write("文件下载时出现错误!");
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
else
{
Page.RegisterStartupScript("提示", "<script type='javascript'>alert('文件不存在!')</script>");
}
}
#endregion

如果各位前辈有好的意见欢迎跟帖 给出一些可以学习更多上传下载的知识!
...全文
54 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
MSDNXGH 2011-08-04
  • 打赏
  • 举报
回复
那。。我就接分了???
蝶恋花雨 2011-08-04
  • 打赏
  • 举报
回复
很好。鼓励下。
hebaobao19880921 2011-08-04
  • 打赏
  • 举报
回复
- - 看来只有我是新手
hebaobao19880921 2011-08-04
  • 打赏
  • 举报
回复
下载

#region WriteFile实现下载
//private void FN_WriteFile()
//{
// try
// {
// string id = Request["id"].ToString();
// Model.File mf = new Model.File();
// BLL.NRBLL bn = new BLL.NRBLL();
// Guid guid = new Guid(id);
// mf.Fileid = guid;
// if (bn.FN_SerchResPath(mf) != null)
// {
// System.IO.FileInfo fileInfo = new System.IO.FileInfo(bn.FN_SerchResPath(mf).Tables["t_file"].Rows[0]["FilePath"].ToString());
// if (fileInfo.Exists == true)
// {
// const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
// byte[] buffer = new byte[ChunkSize];

// Response.Clear();
// System.IO.FileStream iStream = System.IO.File.OpenRead(bn.FN_SerchResPath(mf).Tables["t_file"].Rows[0]["FilePath"].ToString());
// long dataLengthToRead = iStream.Length;//获取下载的文件总大小
// Response.ContentType = "application/octet-stream";
// Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name.ToString()));
// while (dataLengthToRead > 0 && Response.IsClientConnected)
// {
// int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
// Response.OutputStream.Write(buffer, 0, lengthRead);
// Response.Flush();
// dataLengthToRead = dataLengthToRead - lengthRead;
// }
// Response.Close();

// }
// }

// }
// catch (Exception e)
// {

// e.Message.ToString();
// }
//}
#endregion
#region WriteFile分块下载
//public void FN_WriteFileFen()
//{
// string id = Request["id"].ToString();
// NRBLL.File bf = new Asiastar.NRBLL.File();
// Guid guid = new Guid(id);
// if (bf.FN_SerchPathByFileId(guid) != null || bf.FN_SerchPathByFileId(guid).Tables[0].Rows.Count > 0)
// {
// try
// {
// FileInfo fileInfo = new FileInfo(bf.FN_SerchPathByFileId(guid).Tables["ds"].Rows[0]["FilePath"].ToString());
// Response.Clear();
// Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode(fileInfo.Name.ToString()));
// Response.AddHeader("content-length", fileInfo.Length.ToString());
// Response.ContentType = "application/octet-stream";
// Response.ContentEncoding = Encoding.Default;
// Response.WriteFile(bf.FN_SerchPathByFileId(guid).Tables["ds"].Rows[0]["FilePath"].ToString());
// }
// catch (Exception e)
// {
// e.Message.ToString();
// return;
// }

// }
// else
// {
// Page.RegisterStartupScript("", "<script languge='javascript'>alert('文件或文件夹不存在')</script>");
// }
//}

#endregion
#region 流方式下载
public void FN_IoDown()
{
try
{
string id = Request["id"].ToString();
NRModel.File model = new Asiastar.NRModel.File();
NRBLL.File bn = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
model.Fileid = guid;
if (bn.FN_SerchPathByFileId(guid) != null)
{
//以字符流的形式下载文件
FileStream fs = new FileStream(bn.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString(), FileMode.Open);
byte[] bytes = new byte[(int) fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";

//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fs.Name.ToString(), System.Text.Encoding.GetEncoding("GB2312")));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

}
catch (Exception)
{

throw;
}
}
#endregion

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧