现在的位置: 首页 > 综合 > 正文

ASPNET上传文件总结 (转载)

2012年09月04日 ⁄ 综合 ⁄ 共 8872字 ⁄ 字号 评论关闭

2010-03-31 11:54:55|  分类:

Aspnet源码
|  标签:
|字号 订阅

 

1:最简单上传功能利用微软控件FileUpLoad

       string fileName=FileUpload1.FileName;

   // FileUpload1是一个对象有很多的方法来说明上传服务器文件的特征,可以通过属性获取文件名,文件扩展名,文件上传流,文件长度等信息    

//关键方法

FileUpload1.SaveAs(Server.MapPath("~/fileupload/fileupload/"+FileUpload1.FileName));

2:控件上传整个网站文件的大小与响应时间,通过配置web.config中System.web的节点

<httpRuntime maxRequestLength="2097151"/>

3:动态控制每个用户的上传类型和上传大小,在上传事件是完成示例代码如下

//测试文件类型是否符合的变量

        Boolean fileOK = false;

        //设置服务器中保存文件的路径

        String path = Server.MapPath("~/UploadFiles/");

        //判断是否选择了文件

        if (FileUpload1.HasFile)

        {

            //返回文件的扩展名

            String fileExtension =

                System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

            //设置限定的文件类型(如果是每用户不一样,可以动态设置)

            String[] allowedExtensions =

            { ".txt", ".doc", ".xml", ".jpg" };

            //判断用户选择的文件类型是否受限

            for (int i = 0; i < allowedExtensions.Length; i++)

            {

                if (fileExtension == allowedExtensions[i])

                {

                    fileOK = true;

                }

            }

        }

        //如果文件大于1M,则不允许上传(如果每用户不一样,可以下面中的102400中进行设置)

        if (FileUpload1.PostedFile.ContentLength > 1024000)

        {

            fileOK = false;

        }

        //如果文件类型符合

        if (fileOK)

        {

            try

            {

                // 将文件保存到指定的文件夹下

                FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);

                Label1.Text = "文件上传成功!";

            }

            catch

            {

                Label1.Text = "无法实现文件的上传。";

            }

        }

        else

        {

            Label1.Text = "文件类型不对或文件超出1M。";

        }

4:一次上传多个文件的实现思路:

(1)       直接获取用户请求的文件数组

  //上传多文件示例

        //开始上传的功能实现

        lblMessage.Text = "";

        lblMessage.Visible = false;

        //关键点:请求文件集合类

        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");

        //请求表单集合索引采用form

        string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述

        //string albumid=ddlAlbum.SelectedValue.Trim();

        int ifile;

        for (ifile = 0; ifile < files.Count; ifile++)

        {

            if (files[ifile].FileName.Length > 0)

            {

                //关键点:获取请求文件类集合的下标获取一个请求文件

                System.Web.HttpPostedFile postedfile = files[ifile];

                //判断文件大小(可用来动态设置)

                if (postedfile.ContentLength / 1024 > 1024)//单个文件不能大于1024k

                {

                    strmsg.Append(System.IO.Path.GetFileName(postedfile.FileName) + "---不能大于1024k<br>");

                    break;

                }

                //获取文件扩展名

                string fex = Path.GetExtension(postedfile.FileName);

                if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")

                {

                    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---图片格式不对,只能是jpg或gif<br>");

                    break;

                }

            }

        }

        if (strmsg.Length <= 0)    //说明图片大小和格式都没问题

        {

            //以下为创建图库目录

            string dirpath = Server.MapPath("51aspx");

 

            if (Directory.Exists(dirpath) == false)

            {

                Directory.CreateDirectory(dirpath);

            }

            Random ro = new Random();

            int name = 1;

            //关键点:循环遍历

            for (int i = 0; i < files.Count; i++)

            {

                System.Web.HttpPostedFile myFile = files[i];

                string FileName = "";

                string FileExtention = "";

                FileName = System.IO.Path.GetFileName(myFile.FileName);

                string stro = ro.Next(100, 100000000).ToString() + name.ToString();//产生一个随机数用于新命名的图片

                string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;

                if (FileName.Length > 0)//有文件才执行上传操作再保存到数据库

                {

                    FileExtention = System.IO.Path.GetExtension(myFile.FileName);

                    //关键点:保存文件

                    string ppath = Server.MapPath("51aspx") + @" " + NewName + FileExtention;

                    myFile.SaveAs(ppath);

                }

                name = name + 1;//用来重命名规则的变量

            }

            Response.Write("<script>alert('恭喜,图片上传成功!')</script>");

        }

        else

        {

            lblMessage.Text = strmsg.ToString();

            lblMessage.Visible = true;

        }

5:由于AsPNET机制的限制,Aspnet一次只能上传4MB的文件,特大文件不能上传,可以采用第三方组件来上传,并有进度条功能,能多文件上传

第一个组件:Bestcomy.Web.Controls.Upload.dll

使用方法:引入bin中,配置web.config,写方法调用(提供示例代码)

<!--Bestere上传组件注册-->

      <add name="UploadModule" type="Bestcomy.Web.Controls.Upload.UploadModule,Bestcomy.Web.Controls.Upload"/>

第二个组件:Brettle.Web.NeatUpload.dll(示例说明)

配置起来较复杂,不好使用

6:上传特殊功能:(在部分项目中可以使用)

(1)把上传文件以流保存在数据库中(一般不采用这种方式,速度慢)

protected void Button1_Click(object sender, EventArgs e)

    {

        //将图片转化为字节流

        byte[] content= FileToByte(FileUpload1.PostedFile.FileName);

        //保存字节数组到数据库

        SaveFile(content);

        //提示信息

        Response.Write("<script language='javascript'>alert('上传成功');</script>");

    }

    private byte[] FileToByte(string filePath)

    {

        //创建字节空间

        byte[] ib = new Byte[60000];(定义死长度)

        //获取上传的图片的路径

        string strfilepath = filePath;

        //转换成文件流

        FileStream fs = new FileStream(strfilepath, FileMode.Open, FileAccess.Read);

        //将文件内容读进字节数组

        fs.Read(ib, 0, 60000);

        return ib;

    }

    private void SaveFile(byte[] content)

    {

        StringBuilder strSQL = new StringBuilder();

        SqlCommand cmd = new SqlCommand();

        // 创建参数列表

        SqlParameter parm = new SqlParameter("@content", SqlDbType.Image);

 

        // 设置参数的值

        parm.Value = content;

        //将参数添加到SQL命令中

        cmd.Parameters.Add(parm);

 

        // 创建连接字符串

        using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction))

        {

 

            // 添加SQL语句

            strSQL.Append("INSERT INTO fileimageload VALUES(@content)");

            conn.Open();

            //设置SqlCommand的属性

            cmd.Connection = conn;

            cmd.CommandType = CommandType.Text;

            cmd.CommandText = strSQL.ToString();

            //执行添加语句

            cmd.ExecuteNonQuery();

            //清空参数列表

            cmd.Parameters.Clear();

        }

 (2)上传后想获取上传文件的信息

  下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息。

  首先我们定义一个类,用来存储上传的文件的信息(返回时需要)。

public class FileUpLoad

{

 public FileUpLoad()

 {}

 /**////

 /// 上传文件名称

 ///

 public string FileName

 {

  get

  {

   return fileName;

  }

  set

  {

   fileName = value;

  }

 }

 private string fileName;

 /**////

 /// 上传文件路径

 ///

 public string FilePath

 {

  get

  {

   return filepath;

  }

  set

  {

   filepath = value;

  }

 }

 private string filepath;

 /**////

 /// 文件扩展名

 ///

 public string FileExtension

 {

  get

  {

   return fileExtension;

  }

  set

  {

   fileExtension = value;

  }

 }

 private string fileExtension;

}

  另外我们还可以在配置文件中限制上传文件的格式(App.Config):

<?XML version="1.0" encoding="gb2312" ?>

<Application>

<FileUpLoad>

<Format>.jpg|.gif|.png|.bmp

</FileUpLoad>

</Application>

  这样我们就可以开始写我们的上传文件的方法了,如下:

public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)

{

 FileUpLoad fp = new FileUpLoad();

 string fileName,fileExtension;

 string saveName;

 //

 //建立上传对象

 //

 HttpPostedFile postedFile = InputFile.PostedFile;

 fileName = System.IO.Path.GetFileName(postedFile.FileName);

 fileExtension = System.IO.Path.GetExtension(fileName);

 //

 //根据类型确定文件格式

 // 可以这样配置获取配置信息

 AppConfig app = new AppConfig();

 string format = app.GetPath("FileUpLoad/Format");

 //

 //如果格式都不符合则返回

 //

 if(format.IndexOf(fileExtension)==-1)

 {

  throw new ApplicationException("上传数据格式不合法");

 }

 //

 //根据日期和随机数生成随机的文件名

 //

 if(myfileName != string.Empty)

 {

  fileName = myfileName;

 }

 if(isRandom)

 {

  Random objRand = new Random();

  System.DateTime date = DateTime.Now;

  //生成随机文件名

  saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);

  fileName = saveName + fileExtension;

 }

 string phyPath = HttpContext.Current.Request.MapPath(filePath);

 //判断路径是否存在,若不存在则创建路径

 DirectoryInfo upDir = new DirectoryInfo(phyPath);

 if(!upDir.Exists)

 {

  upDir.Create();

 }

 //

 //保存文件

 //

 try

 {

  postedFile.SaveAs(phyPath + fileName);

  fp.FilePath = filePath + fileName;

  fp.FileExtension = fileExtension;

  fp.FileName = fileName;

 }

 catch

 {

  throw new ApplicationException("上传失败!");

 }

 //返回上传文件的信息

 return fp;

}

(3)简易的以二进制上传文件的形式

 这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:

public byte[] UpLoadFile(HtmlInputFile f_IFile)

{

 //获取由客户端指定的上传文件的访问

 HttpPostedFile upFile=f_IFile.PostedFile;

 //得到上传文件的长度

 int upFileLength=upFile.ContentLength;

 //得到上传文件的客户端MIME类型

 string contentType = upFile.ContentType;

 byte[] FileArray=new Byte[upFileLength];

 Stream fileStream=upFile.InputStream; //获得上传的输入流

 fileStream.Read(FileArray,0,upFileLength);

 return FileArray;

}

(4)直接获取网络上的文件以流形式上传

 这一部分主要说如何上传一个Internet上的资源到服务器。

  首先需要引用 System.Net 这个命名空间,然后操作如下:

HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");

HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();

byte[] bytes = new byte[hwr.ContentLength];

Stream stream = hwr.GetResponseStream();

stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));

//HttpContext.Current.Response.BinaryWrite(bytes);

  HttpWebRequest 可以从Internet上读取文件,因此可以很好的解决这个问题。

抱歉!评论已关闭.