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

c#上传文件(一)使用 .net 控件上传文件

2015-07-04 13:38 549 查看
1.html代码:

public int fileMaxContentLength = 1;//最大文件大小,单位M
public int imgMaxWidth = 500;//图片最大宽度,单位px
public int imgMaxHeight = 400;//图片最大高度,单位px
public string fileTypes = ".jpg.png.gif.rar.zip";//文件格式

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { }
}

/// <summary>
/// 上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpLoad_Click(object sender, EventArgs e)
{
if (!this.UpLoadFile.HasFile)
{
//code
return;
}
//HttpPostedFile类提供对客户端已上载的单独文件的访问
HttpPostedFile hpf = this.UpLoadFile.PostedFile;
//文件名
string fileName = Path.GetFileName(hpf.FileName);
//文件扩展名
string extension = System.IO.Path.GetExtension(fileName);
//文件大小,单位字节
int fileContentLength = hpf.ContentLength;
//上传路径
string filePath = Server.MapPath("/Files/");

#region 如果要上传图片,以此判段图片的宽高
//创建数据流
//Stream fileStream = hpf.InputStream;
//通过数据流创建Image对象
//System.Drawing.Image img = System.Drawing.Image.FromStream(hpf.InputStream);
//获取图片的宽度
//int imgWidth = img.Width;
//获取图片的高度
//int imgHeight = img.Height;
#endregion

//判断文件格式
if (!fileTypes.Contains(extension))
{
//code
return;
}
//判断文件大小
if (fileContentLength * 1.0 / (1024 * 1024) > fileMaxContentLength)
{
//code
return;
}

if (!Directory.Exists(filePath))
{
//如果没有此文件夹,则新建
Directory.CreateDirectory(filePath);
}
//保存
hpf.SaveAs(filePath + fileName);
}


cs代码
本人已运行测试,不论代码的质量,可以正常上传文件和图片。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: