JSP文件下载问题
生成CSV帐票时,当DB检索的数据为100行时就出现该错误,如果是99行则没有盖问题。具体代码如下:
public static void createCSV(HttpServletResponse response,
StringBuffer sbFile, String strFileName) {
String strName = strFileName + getSysDate() + ".CSV ";
try {
response.setContentType( "application/csv ");
response.setHeader( "Content-Disposition ", "attachment; filename= "
+ java.net.URLEncoder.encode(strName , "UTF-8 "));
PrintWriter out = new PrintWriter(new OutputStreamWriter(response
.getOutputStream(), "MS932 "));
out.print(sbFile.toString());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
当执行至:PrintWriter out = new PrintWriter(new OutputStreamWriter(response
.getOutputStream(), "MS932 "));该句式就出现异常。
异常信息:getWriter() has already been called for this response
[解决办法]
是不是和buffer的设置有关呀?
[解决办法]
我用的StringBuffer,它的数值应该都在内存中,上述处理是一并输出。
[解决办法]
不会 帮顶
[解决办法]
做下载问题 尽量不要使用 PrintWriter ,可以 用 ServletOutputStream
给你一段我写的下载 方法 Servlet 默认的方法
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
FileInputStream in = null; // 输入流
ServletOutputStream out = null; // 输出流
Staff staff = (Staff) request.getSession().getAttribute(Const.CURRENT_USER);
String mainDeptID = staff.getMainDeptId();
request.setCharacterEncoding( "GBK ");
String para = new String(request.getParameter( "para ").getBytes( "GBK "));
String type = new String(request.getParameter( "type ").getBytes( "GBK "));;
String name = mainDeptID+ "_ " + para + DownLoadFileConstant.FILETYPE ;
String filePath = " ";
if(type.equals( "m ")) {
filePath = Assembled.getAccountDownLoadFilePath()
+ DownLoadFileConstant.MONTHDOWNLOADFILEFOLDNAME
+ File.separator + mainDeptID + File.separator+ para+ File.separator;
} else {
filePath = Assembled.getAccountDownLoadFilePath()
+ DownLoadFileConstant.DATEDOWNLOADFILEFOLDNAME
+ File.separator + mainDeptID + File.separator+ para+ File.separator;
}
response.setContentType( "application/x-msdownload ");
String fileHaderName = URLEncoder.encode(name, "UTF-8 ");
response.setHeader( "Content-disposition ", "attachment; filename= "
+ fileHaderName);
String fileFullName = filePath + name ;
try {
in = new FileInputStream(fileFullName); // 读入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while ((aRead = in.read()) != -1 & in != null) {
out.write(aRead);
}
out.flush();
} catch (Throwable e) {
// log.error( "FileDownload doGet() IO error! ",e);
} finally {
try {
in.close();
out.close();
} catch (Throwable e) {
// log.error( "FileDownload doGet() IO close error! ",e);
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
这个方法可以下载任何格式的文件
[解决办法]
up