j2ee,jsp,servlet文件下载server端

Posted zhchoutai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了j2ee,jsp,servlet文件下载server端相关的知识,希望对你有一定的参考价值。

1.getOutputStream() has already been called for this response

报错的原因:

使用tomcat容器调用response.getOutputStream()方法的时候仅仅可以写二进制文件.

但调用requonse.getWriter()方法时,则仅仅可以在前台打印文本文件.

所以:

假设在jsp页面:

  

outPutStream.flush();
outPutStream.close();
outPutStream=null;
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
这里out和pageContext是jsp的内置对象;


假设在后台:

假设使用response.getWrter,那么前面仅仅能用response.setContentType("text/html");

假设想用二进制流的方式输出,那么就不都够使用response.setContentType("text/html");

假设是想传输文件,推荐:

response.setContentType("application/x-msdownload;charset=utf-8");

同一时候为了防止乱码,response.setCharacterEncoding("utf-8"); 

filename = URLEncoder.encode(filename, "utf-8");


文件下载的代码:

public void getDownLoadBook() throws IOException{
	response.setCharacterEncoding("utf-8");
	String filepath=request.getSession().getServletContext().getRealPath("\\") + "upload\\books\\";
	//通过前台bookId,从数据库中取出文件保存的信息
Book book=this.getBookService().getBook(bookId);
if(book==null)
	{       response.setContentType("text/html");
		PrintWriter writer=response.getWriter();	
		writer.write("<html><body>");
		writer.write("此电子书不存在!");
		writer.write("</body></html>");
		writer.flush();
		writer.close();
		return;
	}
	String filename=book.getSaveName()+"";
	java.io.File file = new java.io.File(filepath + filename);
	if (!file.exists()) {
	         response.setContentType("text/html");
	         PrintWriter writer=response.getWriter();
	         writer.write("<html><body>");
		 writer.write("文件不存在!<br/>"+file.getAbsolutePath()+book.getOriginalName()+"不见了!");
		 writer.write("</body></html>");
		 writer.flush();
		 writer.close();
		 return;
		}
	response.setContentType("application/x-msdownload;charset=utf-8");
	response.setCharacterEncoding("utf-8");
	response.setContentLength((int) file.length());
	filename=book.getOriginalName();
	//编码文件名称,防止乱码
	filename = URLEncoder.encode(filename, "utf-8");
	response.setHeader("Content-Disposition", "attachment; filename=" +filename);
	//得到输出流
        javax.servlet.ServletOutputStream out = response.getOutputStream();
	// 读取文件流
	java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
	// 下载文件, 设置响应头和下载保存的文件名称
	filename=book.getOriginalName();
	if (filename != null && filename.length() > 0) {
	if (fileInputStream != null) {
	int filelen = fileInputStream.available();
	文件太大时内存不能一次读出,要循环
	int i=4096;
	   do{
	      byte a[] = new byte[4096];
	      i=fileInputStream.read(a);
	      out.write(a, 0, i);
	     }while(i>=4096);
	}
	fileInputStream.close();
	out.flush();
	out.close();
		}	 
     }







以上是关于j2ee,jsp,servlet文件下载server端的主要内容,如果未能解决你的问题,请参考以下文章

[J2EE基础]初识JSP和Servlet

Servlet service for Servlet jsp threw exception javax serv

J2EE:如何在 servlet 中获取一个数组列表,并在 JSP 中的隐藏字段中传递?

[转] J2EE基础知识

J2EE——servlet初识

J2EE:Servlet