首页 > 学院 > 开发设计 > 正文

ASP.NET中文件上传控件

2019-11-17 04:07:50
字体:
来源:转载
供稿:网友
<asp:FileUpload /> 文件上传控件

实现一个简单的图片文件上传

//上传文件控件使用:实现上传图片功能,上传图片只能是jpg,gif,bmp三种类型,图片大小不超过60kb

后台代码:

view plaincopy to clipboardPRint?
using System;   
using System.Configuration;   
using System.Data;   
using System.Linq;   
using System.Web;   
using System.Web.Security;   
using System.Web.UI;   
using System.Web.UI.HtmlControls;   
using System.Web.UI.WebControls;   
using System.Web.UI.WebControls.WebParts;   
using System.xml.Linq;   
  
public partial class _Default : System.Web.UI.Page   
{   
    protected void Page_Load(object sender, EventArgs e)   
    {   
        if (!IsPostBack)   
        {   
            imgForFileUp.Visible = false;   
        }   
    }   
    protected void btUp_Click(object sender, EventArgs e)   
    {   
        bool isAllow = false;                       //是否允许上传,默认为false   
        string path = Server.MapPath("image/");     //上传文件保存路径 (相对路径)   
  
        if (fileUp.HasFile)                         //FileUpload控件不为空   
        {   
            string fileType = System.IO.Path.GetExtension(fileUp.FileName).ToLower(); //文件类型   
            string[] allowFile = { ".jpg", ".gif", ".bmp" };// 定义允许上传的文件类型   
            for (int i = 0; i < allowFile.Length; i++)   
            {   
                if ((fileType == allowFile[i]) && fileUp.PostedFile.ContentLength <= 60 * 1024)   
                {   
                    isAllow = true;    //设为true ,即允许上传   
                }   
            }   
        }   
        else  
        {   
            lbForFileUp.Text = "请上传文件!!!";   
        }   
  
  
        if (isAllow == true)   
        {   
            try  
            {   
                //以时间来重命名图片文件名   
                //string newName = DateTime.Now.ToFileTime() + "." + fileType;   
                //保存文件到服务器   
                fileUp.PostedFile.SaveAs(path + fileUp.FileName);   
                //提示信息   
                lbForFileUp.Text = "上传成功!!!";   
                //显示图片   
                imgForFileUp.ImageUrl = "image/" + fileUp.FileName;   
                imgForFileUp.Visible = true;   
            }   
            catch (HttpException ex)   
            {   
                lbForFileUp.Text = "上传失败:" + ex.Message.ToString();   
            }   
        }   
        else if (fileUp.PostedFile.ContentLength > 60 * 1024)   
        {   
            lbForFileUp.Text = "文件大小超过60KB!!!";   
        }   
        else  
        {   
            lbForFileUp.Text = "不可接受的文件类型!!!";   
        }   
  
  
  
    }   
}  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表