Asp.net中用FileUpload控件上传文件

来源:互联网 发布:python开发webservice 编辑:程序博客网 时间:2024/05/17 01:47

后台代码:
protected void Button1_Click(object sender, EventArgs e)
        {
string upTempFileBasePath = this.MapPath(@"~/Member/UserUpLoad/TempUpLoadFiles");
string uploaFileFormat = "|.jpg|.gif|";         //图片的格式也要在配置文件内appSettings节点上配置
string upFileName = Tools.CreateFileName();     //通过一个方法获得随机的文件名
string FileExtension = Path.GetExtension(UploadPhoto.FileName).ToString().Trim(); //取得上传文件的后缀名,带".",后缀名存在才有必要上传文件
string upSaveTempFilePath = upTempFileBasePath + "/" + upFileName + FileExtension;    //上传文件时的路径

if (uploaFileFormat.IndexOf(FileExtension.ToLower()) <= 0)
{
                            Tools.ShowMessage(this.Page, "请上传jpg或gif格式的图片文件!");
                            return;
}
if (UploadPhoto.PostedFile.ContentLength > 153600)
{
                            Tools.ShowMessage(this.Page, "请上传小于150K的图片文件!");   //上传文件的大小(字节)。
                            return;
}
UploadPhoto.SaveAs(upSaveTempFilePath);     //进行保存上传文件
}


前台代码:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>上传文件</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="UploadPhoto" runat="server" />
            <asp:Button ID="btnUpLoadFile" runat="server" Text="确定上传" onclick="btnUpLoadFile_Click" />
        </div>
    </form>
</body>
</html>

要引用: using System.IO


此方法可以判断文件的上传类型和文件大小