问题:
直接用URLEncoder.encode(fileName,"UTF-8"),得到的文件名长度会被截断。
解决方法是:
文件名先用“GB2312”编码,然后用“
ISO8859_1”解码。当然也可以在将文件名保存到数据库之前用“GB2312”编码。
代码如下:
1conn = DBUtil.getConnection();
2 ps = conn.prepareStatement("SELECT FILE_NAME, CONTENT_TYPE, CONTENT FROM PUB_JOB_ATTACHMENTS WHERE ATTACHID = ?");
3 ps.setString(1,getAttachId());
4 rs = ps.executeQuery();
5 if(rs.next())
6 {
7 //java.net.URLEncoder.encode(rs.getString("FILE_NAME"), "UTF-8")
8 response.setContentType(rs.getString("CONTENT_TYPE"));
9 String fileName=rs.getString("FILE_NAME");
10 fileName=URLEncoder.encode(fileName,"GB2312");
11 fileName=URLDecoder.decode(fileName, "ISO8859_1");
12 response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
13 Blob content = rs.getBlob("CONTENT");
14 InputStream ins = content.getBinaryStream();
15 byte buffer[] = new byte[1024];
16 int length = -1;
17 outs = response.getOutputStream();
18 while((length = ins.read(buffer)) != -1)
19 outs.write(buffer, 0, length);
20 ins.close();
21 outs.flush();
22 }