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", "attachmentfilename=\""+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
}
}
要不给你一个可以直接调用的方法吧,你也可以对比修改
/*** 下载文件
*
* @param request
* @param response
* @param storeName 被下载文件路径
* @param contentType 推荐:application/octet-stream
* @param realName 下载时显示的文件名称
* 返闷陵@throws Exception
*/
public static void download(HttpServletRequest request, HttpServletResponse response, String storeName, String contentType, String realName)
throws Exception {
request.setCharacterEncoding("UTF-8")
BufferedInputStream bis = null
漏戚 BufferedOutputStream bos = null
try {
String downLoadPath = storeName
long fileLength = new File(downLoadPath).length()
response.setContentType(contentType)
response.setHeader("Content-disposition", "attachment filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"))
response.setHeader("Content-Length", String.valueOf(fileLength))
bis = new BufferedInputStream(new FileInputStream(downLoadPath))
bos = new BufferedOutputStream(response.getOutputStream())
byte[] buff = new byte[2048]
int bytesRead
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead)
}
} catch (Exception e) {
e.printStackTrace()
throw e
罩饥 } finally {
if (bis != null)
bis.close()
if (bos != null)
bos.close()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)