c从服务器文件代码.docx
C从服务器下载文件代码一、//TRANSMITFILE实现下载PROTECTEDVOIDBUTTON1_CLICKOBJECTSENDER,EVENTARGSE{/微软为RESPONSE对象提供了一个新的方法TRANSMITFILE来解决使用RESPONSEBINARYWRITE下载超过400MB的文件时导致ASPNET_WP进程回收而无法成功下载的问题。代码如下/RESPONSECONTENTTYPE“APPLICATION/XZIPCOMPRESSED“RESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAMEZZIP“STRINGFILENAMESERVERMAPPATH“DOWNLOAD/ZZIP“RESPONSETRANSMITFILEFILENAME}二、//WRITEFILE实现下载PROTECTEDVOIDBUTTON2_CLICKOBJECTSENDER,EVENTARGSE{/USINGSYSTEMIO/STRINGFILENAME“ASDTXT“//客户端保存的文件名STRINGFILEPATHSERVERMAPPATH“DOWNLOAD/AAATXT“//路径FILEINFOFILEINFONEWFILEINFOFILEPATHRESPONSECLEARRESPONSECLEARCONTENTRESPONSECLEARHEADERSRESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAME“FILENAMERESPONSEADDHEADER“CONTENTLENGTH“,FILEINFOLENGTHTOSTRINGRESPONSEADDHEADER“CONTENTTRANSFERENCODING“,“BINARY“RESPONSECONTENTTYPE“APPLICATION/OCTETSTREAM“RESPONSECONTENTENCODINGSYSTEMTEXTENCODINGGETENCODING“GB2312“RESPONSEWRITEFILEFILEINFOFULLNAMERESPONSERESPONSEEND}三、//WRITEFILE分块下载PROTECTEDVOIDBUTTON3_CLICKOBJECTSENDER,EVENTARGSE{STRINGFILENAME“AAATXT“//客户端保存的文件名STRINGFILEPATHSERVERMAPPATH“DOWNLOAD/AAATXT“//路径SYSTEMIOFILEINFOFILEINFONEWSYSTEMIOFILEINFOFILEPATHIFFILEINFOEXISTSTRUE{CONSTLONGCHUNKSIZE102400//100K每次读取文件,只读取100K,这样可以缓解服务器的压力BYTEBUFFERNEWBYTECHUNKSIZERESPONSECLEARSYSTEMIOFILESTREAMISTREAMSYSTEMIOFILEOPENREADFILEPATHLONGDATALENGTHTOREADISTREAMLENGTH//获取下载的文件总大小RESPONSECONTENTTYPE“APPLICATION/OCTETSTREAM“RESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAME“HTTPUTILITYURLENCODEFILENAMEWHILEDATALENGTHTOREAD0//读取的大小RESPONSEOUTPUTSTREAMWRITEBUFFER,0,LENGTHREADRESPONSEDATALENGTHTOREADDATALENGTHTOREADLENGTHREAD}RESPONSECLOSE}}四、//流方式下载PROTECTEDVOIDBUTTON4_CLICKOBJECTSENDER,EVENTARGSE{STRINGFILENAME“AAATXT“//客户端保存的文件名STRINGFILEPATHSERVERMAPPATH“DOWNLOAD/AAATXT“//路径//以字符流的形式下载文件FILESTREAMFSNEWFILESTREAMFILEPATH,FILEMODEOPENBYTEBYTESNEWBYTEINTFSLENGTHFSREADBYTES,0,BYTESLENGTHFSCLOSERESPONSECONTENTTYPE“APPLICATION/OCTETSTREAM“//通知浏览器下载文件而不是打开RESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAME“HTTPUTILITYURLENCODEFILENAME,SYSTEMTEXTENCODINGUTF8RESPONSEBINARYWRITEBYTESRESPONSERESPONSEEND}//PUBLICVOIDDOWNLOADFILESYSTEMWEBUIPAGEWEB,STRINGFILENAMEWHENUSERDOWNLOAD,STRINGFILEBODY{WEBRESPONSECLEARHEADERSWEBRESPONSECLEARWEBRESPONSEEXPIRES0WEBRESPONSEBUFFERTRUEWEBRESPONSEADDHEADER“ACCEPTLANGUAGE“,“ZHTW“// 文件名称WEBRESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAME “SYSTEMWEBHTTPUTILITYURLENCODEFILENAMEWHENUSERDOWNLOAD,SYSTEMTEXTENCODINGUTF8“ “WEBRESPONSECONTENTTYPE“APPLICATION/OCTETSTREAM“// 文件内容WEBRESPONSEWRITEFILEBODY//WEBRESPONSEEND}//上面这段代码是下载一个动态产生的文本文件,若这个文件已经存在于服务器端的实体路径,则可以通过下面的函数PUBLICVOIDDOWNLOADFILEBYFILEPATHSYSTEMWEBUIPAGEWEB,STRINGFILENAMEWHENUSERDOWNLOAD,STRINGFILEPATH{WEBRESPONSECLEARHEADERSWEBRESPONSECLEARWEBRESPONSEEXPIRES0WEBRESPONSEBUFFERTRUEWEBRESPONSEADDHEADER“ACCEPTLANGUAGE“,“ZHTW“//文件名称WEBRESPONSEADDHEADER“CONTENTDISPOSITION“,“ATTACHMENTFILENAME “SYSTEMWEBHTTPUTILITYUR