对于下载时新打开一窗口下载,下载完后需要关闭的
一种:对于较小文件可以有效:
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,在客户的端的解释可能是不一样的。
有想法请回复,欢迎讨论
新闻热点
疑难解答
图片精选