多看帮助文档,不让自己OUT了

ASP.NET 1.1 文件上传优化与新技术引入

在ASP.NET1.1的时候,上传文件代码:

//上传版面图片
private void UpLoadPicture(MagazineLayout layout)
{
//不上传附件时直接返回0作为附件ID
if (String.IsNullOrEmpty(PictureName.PostedFile.FileName))
{
return;
}

string oldPicturePath = "";
if (!string.IsNullOrEmpty(layout.PicturePath))
{
oldPicturePath
= Server.MapPath(layout.PicturePath);
}

const string path = "/MagazineLayout/";

//文件名(文件名+后缀)
layout.PictureName = PictureName.PostedFile.FileName.Substring(PictureName.PostedFile.FileName.LastIndexOf('\\') + 1);

//文件扩展名
string fileTitleSuf = layout.PictureName.Substring(layout.PictureName.LastIndexOf('.'));

//文件保存虚拟路径
layout.PicturePath = path + Session["UserId"] + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + fileTitleSuf;

//文件保存物理路径
string filePath = Server.MapPath(layout.PicturePath);

try
{
if (File.Exists(filePath.Replace("\\", "\\\\")))
{
Response.Write(
"<script>alert('上传文件名称重复,操作未成功!')</script>");
}
else
{
//文件|附件保存到文件夹
PictureName.PostedFile.SaveAs(filePath);

//如果是覆盖,则删掉原来的文件
if (!String.IsNullOrEmpty(oldPicturePath))
{
//重新上传了一次附件时,将原来的附件删除
if (File.Exists(oldPicturePath))
{
File.Delete(oldPicturePath);
}
}

//信息保存到数据库
MagazineManager.CreateUpdateDeleteMagazineLayout(layout, MagazineDataProviderAction.UpdateMagazine);
}
}
catch (Exception err)
{
Response.Write(err.Message);
Response.Write(
"<script>alert('文件上传失败!');</script>");
}

return;
}

偶然的机会看了下新的API,太让人震撼了,原来自己OUT那么远了。。。。。。

private void UpLoadFile(MagazineLayout layout)
{
if (String.IsNullOrEmpty(PictureName.PostedFile.FileName))
{
return;
}

if(!String.IsNullOrEmpty(layout.PicturePath))
{
//删除老的文件
DeleteOldFile(layout.PicturePath);
}

const string path = "/MagazineLayout/";

try
{
//文件后缀名
string fileExt = Path.GetExtension(PictureName.PostedFile.FileName);

//新文件名(文件名+后缀名)
string fileName = Session["UserId"] + DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;

//原文件名(文件名+后缀)
layout.PictureName = Path.GetFileName(PictureName.PostedFile.FileName);

//文件保存虚拟路径
layout.PicturePath = path + fileName;

string dir = Request.MapPath(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

//保存文件
PictureName.PostedFile.SaveAs(Path.Combine(dir + fileName));

//信息保存到数据库
MagazineManager.CreateUpdateDeleteMagazineLayout(layout, MagazineDataProviderAction.UpdateMagazine);
}
catch (Exception err)
{
Response.Write(err.Message);
Response.Write(
"<script>alert('文件上传失败!');</script>");
}

}

//文件删除方法
private static void DeleteOldFile(string filePath)
{
//重新上传了一次附件时,将原来的附件删除
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}

在.NET Framework 4 很多方法已经封装好了,所有新的API不能落下了,赶紧补

转载于:https://www.cnblogs.com/acafaxy/archive/2011/08/05/2128821.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值