今天在使用struts2 進行文件下載是,總報錯:
java.lang.IllegalStateException: getOutputStream() has already been called for this respons
......
解決辦法:
把對應的action的返回設置為空,即可輕松解決。
例如:
public class DownloadFileAction extends ActionSupport implements ServletRequestAware, ServletResponseAware { /** * */ private static final long serialVersionUID = -7448748577778248376L; private HttpServletRequest request; private HttpServletResponse response; private String savePath; @Override public String execute() throws Exception { String fileName=request.getParameter("fileName"); String fullPath=getSavePath()+"//"+fileName; fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1"); InputStream is=new FileInputStream(fullPath); int len=0; byte []buffers=new byte[1024]; response.reset(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment;filename=\""+fileName+"\""); OutputStream os = null; //把文件內容通過輸出流打印到頁面上供下載 while((len=is.read(buffers))!=-1){ os=response.getOutputStream(); os.write(buffers, 0, len); } is.close(); os.flush(); //return SUCCESS; //會報錯:java.lang.IllegalStateException: getOutputStream() has already been called for this respons return null;//ok } public void setServletRequest(HttpServletRequest req) { this.request=req; } public void setServletResponse(HttpServletResponse resp) { this.response=resp; } @SuppressWarnings("deprecation") public String getSavePath() { return request.getRealPath(savePath); } public void setSavePath(String savePath) { this.savePath = savePath; } }