分享

asp.net中文件如何上传到服务器上

 修行的嘟嘟 2010-06-01
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace SuAn
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.filepost.PostedFile.FileName == "")
            {
                Response.Write("上传文件不能为空!");
                return;
            }
            try
            {
                string  Path = Server.MapPath("upload/");//设置服务器端路径
                string filePath = this.filepost.PostedFile.FileName;//获取客户端实际路径
                string fileName = filePath.Substring(filePath.LastIndexOf("\\")+1);//获取文件名称
                string serverPath = Path + fileName;//上传的文件保存到服务器端的路径
                System.Text.StringBuilder buider = new System.Text.StringBuilder();//上传的文件信息:可变字符串
                buider.Append("上传文件的类型:"+this.filepost.PostedFile.ContentType.ToString()+"");
                buider.Append("客户端文件地址:"+this.filepost.PostedFile.FileName+"");
                buider.Append("上传文件名称:"+fileName);
                buider.Append("上传文件的扩展名:"+filePath.Substring(fileName.LastIndexOf(".")+1));
                buider.Append("上传文件的大小:"+this.filepost.PostedFile.ContentLength/1024+"k"+"");
                if (System.IO.File.Exists(serverPath))
                {
                    Response.Write("这个文件在服务器上已经存在,请不要重复上传!");
                    return;
                }
                string str = fileName.Substring(fileName.LastIndexOf(".")+1);//获取文件后缀名
                if (str == "jpg" || str == "rar" || str == "ppt")
                {
                    Response.Write("对不起,该类型文件不能被上传!");
                    return;
                }
                if (this.filepost.PostedFile.ContentLength >2048)
                {
                    Response.Write("对不起,文件不能超过2K");
                    return;
                }
                this.filepost.PostedFile.SaveAs(serverPath);//上传保存文件
                this.lblMessage.Text = buider.ToString();
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
           
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多