欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

更有效的文件下载功能

程序员文章站 2022-06-25 16:05:11
1.普通下载:         //下载文件的路径     &...

1.普通下载:


        //下载文件的路径
        string path=server.mappath("广告.jpg");
        //下载文件的名称
        string filename = "广告.jpg";
        system.io.fileinfo todownload = new system.io.fileinfo(path);
        response.clear();
        if (system.io.path.getextension(filename) == ".jpg")
        ...{
            response.addheader("content-disposition", "attachment;filename=new_" + httputility.urlencode(todownload.name));
            response.contenttype = "application/x-zip-compressed";
            response.transmitfile(path);
            response.end();
        }
 

2.大文件分成小块下载:


        //下载文件的路径
        string path = server.mappath("广告.jpg");
        //下载文件的名称
        string filename = "广告.jpg";
        system.io.fileinfo todownload = new system.io.fileinfo(path);

        if (todownload.exists == true)
        {
            const long chunksize = 10000;
            byte[] buffer = new byte[chunksize];

            response.clear();
            system.io.filestream istream = system.io.file.openread(path);
            long datalengthtoread = istream.length;
            response.contenttype = "application/octet-stream";
            response.addheader("content-disposition", "attachment; filename=new_" + httputility.urlencode(todownload.name));
            while (datalengthtoread > 0 && response.isclientconnected)
            {
                int lengthread = istream.read(buffer, 0, convert.toint32(chunksize));
                response.outputstream.write(buffer, 0, lengthread);
                response.flush();
                datalengthtoread = datalengthtoread - lengthread;
            }
            response.close();
        }

 

 


摘自 爱智旮旯