标题 | asp.net下载大文件的实现方法 |
内容 | 本文实例讲述了asp.net下载大文件的实现方法。分享给大家供大家参考。具体分析如下: 当我们的网站需要支持下载大文件时,如果不做控制可能会导致用户在访问下载页面时发生无响应,使得浏览器崩溃。可以参考如下代码来避免这个问题。 关于此代码的几点说明: 1. 将数据分成较小的部分,然后将其移动到输出流以供下载,从而获取这些数据。 2. 根据下载的文件类型来指定 response.contenttype 。(参考oschina的这个网址可以找到大部分文件类型的对照表:) 3. 在每次写完response时记得调用 response.flush() 4. 在循环下载的过程中使用 response.isclientconnected 这个判断可以帮助程序尽早发现连接是否正常。若不正常,可以及早的放弃下载,以释放所占用的服务器资源。 5. 在下载结束后,需要调用 response.end() 来保证当前线程可以在最后被终止掉。 代码如下: using system; namespace webapplication1 { public partial class downloadfile : system.web.ui.page { protected void page_load(object sender, eventargs e) { system.io.stream istream = null; // buffer to read 10k bytes in chunk: byte[] buffer = new byte[10000]; // length of the file: int length; // total bytes to read. long datatoread; // identify the file to download including its path. string filepath = server.mappath(/) +./files/textfile1.txt; // identify the file name. string filename = system.io.path.getfilename(filepath); try { // open the file. istream = new system.io.filestream(filepath, system.io.filemode.open, system.io.fileaccess.read, system.io.fileshare.read); // total bytes to read. datatoread = istream.length; response.clear(); response.clearheaders(); response.clearcontent(); response.contenttype = text/plain; // set the file type response.addheader(content-length, datatoread.tostring()); response.addheader(content-disposition, attachment; filename= + filename); // read the bytes. while (datatoread > 0) { // verify that the client is connected. if (response.isclientconnected) { // read the data in buffer. length = istream.read(buffer, 0, 10000); // write the data to the current output stream. response.outputstream.write(buffer, 0, length); // flush the data to the html output. response.flush(); buffer = new byte[10000]; datatoread = datatoread - length; } else { // prevent infinite loop if user disconnects datatoread = -1; } } } catch (exception ex) { // trap the error, if any. response.write(error : + ex.message); } finally { if (istream != null) { //close the file. istream.close(); } response.end(); } } } } 希望本文所述对大家的asp.net程序设计有所帮助。 |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。