当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET中文件上传下载方法集合

ASP.NET中文件上传下载方法集合

2018年04月29日  | 移动技术网IT编程  | 我要评论

哲学文章,久草免费线资源站,花花新郎你别逃

  文件的上传下载是我们在实际项目开发过程中经常需要用到的技术,这里给出几种常见的方法,本文主要内容包括:

  1、如何解决文件上传大小的限制
  2、以文件形式保存到服务器
  3、转换成二进制字节流保存到数据库以及下载方法
  4、上传internet上的资源

  第一部分:

    首先我们来说一下如何解决asp.net中的文件上传大小限制的问题,我们知道在默认情况下asp.net的文件上传大小限制为2m,一般情况下,我们可以采用更改web.config文件来自定义最大文件大小,如下:

<httpruntime executiontimeout="300" maxrequestlength="40960" usefullyqualifiedredirecturl="false"/>

  这样上传文件的最大值就变成了4m,但这样并不能让我们无限的扩大maxrequestlength的值,因为asp.net会将全部文件载入内存后,再加以处理。解决的方法是利用隐含的httpworkerrequest,用它的getpreloadedentitybody和readentitybody方法从iis为asp.net建立的pipe里分块读取数据。实现方法如下:

iserviceproviderprovider=(iserviceprovider)httpcontext.current;
httpworkerrequestwr=(httpworkerrequest)provider.getservice(typeof(httpworkerrequest));
byte[]bs=wr.getpreloadedentitybody();
.
if(!wr.isentireentitybodyispreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.readentitybody(bs2,n)>0)
{
..
}
}

  这样就可以解决了大文件的上传问题了。

  第二部分:

    下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息.首先我们定义一个类,用来存储上传的文件的信息(返回时需要)。

public class fileupload
{
   public fileupload()
   {

   }
/**//// <summary>
        /// 上传文件名称
        /// </summary>
        public string filename
        {
            get
            {
                return filename;
            }
            set
            {
                filename = value;
            }
        }
        private string filename;

        /**//// <summary>
        /// 上传文件路径
        /// </summary>
        public string filepath
        {
            get
            {
                return filepath;
            }
            set
            {
                filepath = value;
            }
        }
        private string filepath;

       
        /**//// <summary>
        /// 文件扩展名
        /// </summary>
        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</format>
    </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;
        }

  然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就ok了。

  第三部分:

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

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);

}

  这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一个aspx页面,然后在它的page_load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无法打开某站点的错误,我一般采用下面的方法:

  首先,在web.config中加入:

<add verb="*" path="openfile.aspx" type="ruixinoa.web.baseclass.openfile, ruixinoa.web"/>

  这表示我打开openfile.aspx这个页面时,系统就会自动转到执行ruixinoa.web.baseclass.openfile 这个类里的方法,具体实现如下:

using system;
using system.data;
using system.web;
using system.io;
using ruixin.workflowdb;
using rxsuite.base;
using rxsuite.component;
using ruixinoa.businessfacade;

namespace ruixinoa.web.baseclass
{
    /**//// <summary>
    /// netufile 的摘要说明。
    /// </summary>
    public class openfile : ihttphandler
    {
        public void processrequest(httpcontext context)
        {

            //从数据库中取出要下载的文件信息
            ruixinoa.businessfacade.rx_oa_filemanager os = new rx_oa_filemanager();
            entitydata data = os.getfiledetail(id);

            if(data != null && data.tables["rx_oa_file"].rows.count > 0)
            {
                datarow dr = (datarow)data.tables["rx_oa_file"].rows[0];

                context.response.buffer = true;
                context.response.clear();
                context.response.contenttype = dr["ccontenttype"].tostring();
                context.response.addheader("content-disposition","attachment;filename=" + httputility.urlencode(dr["ctitle"].tostring()));
                context.response.binarywrite((byte[])dr["ccontent"]);
                context.response.flush();
                context.response.end();
            }
                       

        }

        public bool isreusable
        {

            get { return true;}
        }
    }
}

  执行上面的方法后,系统会提示用户选择直接打开还是下载。这一部分我们就说到这里。

  第四部分:

    这一部分主要说如何上传一个internet上的资源到服务器。前面我们有一篇文章详细介绍了使用方法,这里我不再多说。

  第五部分:总结

    今天简单的介绍了几种文件上传与下载的方法,都是在实际的项目开发中经常需要用到的,可能还有不完善的地方,希望大家可以互相交流一下项目开发中的经验。写的不好的地方,请指正,谢谢!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网