java servlet 用firefox下载文件,文件名有空格的问题
By:Roy.LiuLast updated:2013-09-24
下载文件,貌似是个很简单的活,最基本的方法有两种,一种是根据文件路径,直接下载。这种方法给一个url链接就可以了,或者是查询到路径,重定向就可以解决。另外一种情况是 通过文件流方式下载,这就是我想说的问题, 在这种情况下,如果你给下载的文件名中间有空格分隔的话,在firefox 下是会出问题的。也就是文件名被split 了,根据空格split 掉了。所以要经过一点点小的处理才能完整下载。
比如有如下servlet 下载文件.
请注意这里文件名 String fileName = "my download test file"; 中间有空格,如果在ie,chrome下去下载文件,肯定没有问题,但如果在firefox 名字就会变为my ,也就是说被空格截断了,而且只认第一个空格前的名字。
其实解决的方法也很简单,那就是更改这个地方
说白了,就是用 双引号把文件名引起来就可以解决这个问题。
比如有如下servlet 下载文件.
private void download(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String fileName = "my download test file";
String encoding = request.getParameter("code");
if ((encoding == null) || (encoding == "undefined")) {
encoding = "utf-8";
}
fileName = Utils.urlDecoder(fileName, new String[] { encoding });
System.out.println(fileName);
String[] dots = fileName.split("[.]");
String postfix = dots[(dots.length - 1)];
if (postfix != null) {
if (("xls".equals(postfix)) || ("xlsx".equals(postfix))) {
response.setContentType("application/msexcel");
}
else if (("doc".equals(postfix)) || ("docx".equals(postfix))) {
response.setContentType("application/msword");
}
else if (("zip".equals(postfix)) || ("rar".equals(postfix))) {
response.setContentType("application/zip");
}
else if (("gif".equals(postfix)) || ("jpg".equals(postfix)) || ("png".equals(postfix)) || ("jpeg".equals(postfix))) {
response.setContentType("image/gif");
}
else if ("pdf".equals(postfix)) {
response.setContentType("image/pdf");
}
else
response.setContentType("application/text");
}
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(REAL_PATH + fileName));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
} catch (Exception localException) {
} finally {
try {
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意这里文件名 String fileName = "my download test file"; 中间有空格,如果在ie,chrome下去下载文件,肯定没有问题,但如果在firefox 名字就会变为my ,也就是说被空格截断了,而且只认第一个空格前的名字。
其实解决的方法也很简单,那就是更改这个地方
response.setHeader("Content-disposition", "attachment;filename=\"" + fileName +"\"");
说白了,就是用 双引号把文件名引起来就可以解决这个问题。
From:一号门
Previous:在小区里面发现一只猫与壁虎在打架PK
Next:简单的java性能调试方法

COMMENTS