對于下載時新打開一窗口下載,下載完后需要關閉的
一種:對于較小文件可以有效:
system.io.fileinfo file = new system.io.fileinfo("f://mp3//mp3//別哭我最愛的人.mp3");
response.clear();
response.clearheaders();
response.buffer = false;
response.charset="gb2312";
response.contentencoding=system.text.encoding.utf8;
response.contenttype = "application/octet-stream";
response.addheader("content-disposition", "attachment; filename="+server.urlencode("別哭我最愛的人.mp3"));
response.addheader("content-length", file.length.tostring());
response.writefile(file.fullname);
response.flush();
response.end();
該代碼可以實現輸出文件并將新打開的窗體關閉。
另一種對于大文件,我們用上述代碼不是較好,因為上述代碼是將文件全緩存于服務器后才輸出的,如果你的服務器流量大,且文件較大,不建議用以上方法。
以下我測試過,較好能解決:
public static bool responsefile(httprequest _request,httpresponse _response,string _filename,string _fullpath, long _speed)
{
try
{
filestream myfile = new filestream(_fullpath, filemode.open, fileaccess.read, fileshare.readwrite);
binaryreader br = new binaryreader(myfile);
try
{
_response.addheader("accept-ranges", "bytes");
_response.buffer = false;
long filelength = myfile.length;
long startbytes = 0;
int pack = 10240; //10k bytes
int sleep = (int)math.floor(1000 * pack / _speed) + 1;
if (_request.headers["range"] != null)
{
_response.statuscode = 206;
string[] range = _request.headers["range"].split(new char[] {'=', '-'});
startbytes = convert.toint64(range[1]);
}
_response.addheader("content-length", (filelength - startbytes).tostring());
if (startbytes != 0)
{
_response.addheader("content-range", string.format(" bytes {0}-{1}/{2}", startbytes, filelength-1, filelength));
}
_response.addheader("connection", "keep-alive");
_response.contenttype = "application/octet-stream";
_response.addheader("content-disposition","attachment;filename=" + httputility.urlencode(_filename,system.text.encoding.utf8) );
br.basestream.seek(startbytes, seekorigin.begin);
int maxcount = (int) math.floor((filelength - startbytes) / pack) + 1;
for (int i = 0; i < maxcount; i++)
{
if (_response.isclientconnected)
{
_response.binarywrite(br.readbytes(pack));
thread.sleep(sleep);
}
else
{
i=maxcount;
}
}
_response.flush();
}
catch
{
return false;
}
finally
{
br.close();
myfile.close();
}
}
catch
{
return false;
}
return true;
}
這一種代碼也是借簽網上的
它也可以實現輸出文件并關閉新打開幕窗體
另外在測試當中發現,服務器端與客戶的操作系統不同
也會有一些意想不到的事情發生
一般來說,用以上代碼,如不能正常關閉,你可以查閱瀏覽器的設置,在高級中。
再者,你可以修改不同的輸出內容類型response.contenttype = "application/octet-stream";因為不同的contenttype,在客戶的端的解釋可能是不一樣的。
有想法請回復,歡迎討論
新聞熱點
疑難解答
圖片精選