星期四, 十月 23, 2008

Servlet download 如何为已知的 MIME 类型激活“文件下载”对话框?

根据微软的一个文章:http://support.microsoft.com/kb/q260519/
参考如下:
您可以使用 Content-disposition 头来覆盖此默认行为。其格式是:
Content-disposition: attachment; filename=fname.ext
ASP:代码

Response.AddHeader "content-disposition","attachment; filename=fname.ext"

Servlet代码:
realName="yourfiel.n";
response.addHeader("Content-disposition","attachment; filename="+realName);
//realName如果是汉字编码会造成出现不了制定的文件名的情况,需要编码
//把以上代码修改为
//response.addHeader("Content-disposition","attachment; filename="+java.net.URLEncoder.encode(realName,"UTF-8"));

response.setIntHeader("Content-length", (int)rs.getBlob("ATTACH_FILE").length());

InputStream is = rs.getBinaryStream("ATTACH_FILE");

byte[] buf = new byte[3000];
int read = 0;
while ((read = is.read(buf)) > 0)
{
// fos.write(buf, 0, read);
outs.write(buf, 0, read);
}
// fos.close();
is.close();
outs.flush();
// outs.close();
}