《WebForm开发系列之控件篇》Item1 FileUpload

1.上传类:UpLoad.cs

 

代码
/// <summary>
/// 文件上传
/// </summary>
public class Upload
{
public Upload() { }

/// <summary>
/// 文件上传 按照当前时间自动命名!
/// </summary>
/// <param name="fu">传入上传控件的名称</param>
/// <param name="address">传入文件保存的虚拟路径</param>
/// <returns></returns>
public static UpModel UpFile(FileUpload fu, string address)
{
string Name = fu.FileName;
string TimeName = DateTime.Now.ToString("yyyyMMddhhmmss");
string fe = Name.Substring(Name.LastIndexOf(".") + 1);
string SevaSoft = System.Web.HttpContext.Current.Server.MapPath(address);
System.IO.Directory.CreateDirectory(SevaSoft);
string Soft = SevaSoft + TimeName + "." + fe;
fu.SaveAs(Soft);
UpModel File
= new UpModel();
File.address
= TimeName + "." + fe;
File.size
= (fu.PostedFile.ContentLength / 1024).ToString();

return File;
}
}

/// <summary>
/// 文件上传数据实体
/// </summary>
public class UpModel
{
public UpModel() { }

private string _address;
private string _size;

/// <summary>
/// 文件路径
/// </summary>
public string address
{
get { return _address; }
set { _address = value; }
}

/// <summary>
/// 文件大小
/// </summary>
public string size
{
get { return _size; }
set { _size = value; }
}
}

 

2.窗体设计器:

 

代码
<tr>
<td class="p_a_t">
显 示 图 片:
</td>
<td align="left">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button2" runat="server" Text="文档上传" OnClick="UpFile_Click"/> <font color="red">请上传要提供显示的图片</font>
</td>
<tr class="p_a_t">
<td >图 片 路 径:</td>
<td align="left">&nbsp;<asp:Label ID="Label1" runat="server" />
</td>
</tr> </tr>

 

3.代码设计器

 

代码
protected void UpFile_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
UpModel File
= Upload.UpFile(FileUpload1, "UploadImg\\Picture\\");
Label1.Text
= File.address.ToString();
//Label2.Text = File.size.ToString() + " Kb ";
}
else Response.Write("<script>alert('请选择要显示的图片!');history.go(-1);</script>");
}

 

 4.允许上传文件的扩展名

 

代码
///<summary>
///是否允许该扩展名上传
///</summary>
///<paramname = "HtmlFile">HtmlInputFile控件</param>
///<returns>允许则返回true,否则返回false</returns>
public bool IsAllowExtension(HtmlInputFile HtmlFile)
{
string StrExtension = null;
string StrOldFilePath = null;
string[] ArrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };

if (HtmlFile.PostedFile.FileName != string.Empty)
{
StrOldFilePath
= HtmlFile.PostedFile.FileName; //取得上传文件的扩展名
StrExtension = StrOldFilePath.Substring(StrOldFilePath.LastIndexOf("."));

//判断该扩展名是否合法
for (int i = 0; i < ArrExtension.Length; i++)
{
if (StrExtension.Equals(ArrExtension[i])) return true;
}
}
return false;
}

 

 

 

作者:Sue

出处:http://www.cnblogs.com/Sue_
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2010-01-28 11:47  Sue_娜  阅读(242)  评论(0编辑  收藏  举报