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

时间:2023-03-09 17:32:01
c#上传文件(一)使用 .net 控件上传文件

1.html代码:

<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload runat="server" ID="UpLoadFile"/>
<asp:Button runat="server" ID="btnUpLoad" OnClick="btnUpLoad_Click" Text="上传"/>
</div>
</form>
</body>

html代码

2.后台代码:

public int fileMaxContentLength = ;//最大文件大小,单位M
public int imgMaxWidth = ;//图片最大宽度,单位px
public int imgMaxHeight = ;//图片最大高度,单位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 / ( * ) > fileMaxContentLength)
{
//code
return;
} if (!Directory.Exists(filePath))
{
//如果没有此文件夹,则新建
Directory.CreateDirectory(filePath);
}
//保存
hpf.SaveAs(filePath + fileName);
}

cs代码

本人已运行测试,不论代码的质量,可以正常上传文件和图片。