ITeye博客

关于struts文件下载的一个问题

jacobcookie · 2013-03-21 13:31 · struts · 编程语言 · Markdown

public class DownloadAction extends Action {

	//问题:下载文件时,后台老是抛出异常:
	//getOutputStream() has already been called for this response
	//不知这段代码哪里出了问题没有.谢谢大家的帮忙.
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String oldFileName=request.getParameter("oldFileName");
		//弹出一个框框
		response.setContentType("text/html;charset=utf-8");
		//设置一个头,告诉浏览器有文件要下载  对中文要进行url编码
		try {
			response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}	
		
		String newFileName=request.getParameter("newFileName");	
		String fileAllPath=this.getServlet().getServletContext().getRealPath("/file")+"\\"+newFileName;
	
		InputStream is=null;
		OutputStream os=null;
		try {
			is=new FileInputStream(fileAllPath);
			os=response.getOutputStream();
			int len;
			byte[] buf=new byte[1024];
			while((len=is.read(buf))>0){
				os.write(buf,0,len);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=is){
					is.close();
				}
				if(null!=os){
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return mapping.findForward("back");
	}
}

评论(3)

  1. #3 楼 · jacobcookie · 2013-11-25 21:09

    这个问题再次遇到过,好像是设置return null;解决的。

  2. #2 楼 · jacobcookie · 2013-03-21 19:32

    hottymg writes:

    以前在jsp中用实现简单文件下载也遇到过这个问题

    最终加了 [code=java] out.clear(); out = pageContext.pushBody() [/code];

    解决的 你可以对应改改试试

    新手见解 :wink:

    你这是写在jsp里的吧,我试了,没起作用啊,还是谢谢你.

  3. #1 楼 · hottymg · 2013-03-21 16:22

    以前在jsp中用实现简单文件下载也遇到过这个问题

    最终加了

    
    out.clear();
    out = pageContext.pushBody()
    
    

    ;

    解决的 你可以对应改改试试

    新手见解 :wink:

评论功能维护中,当前仅展示历史评论。