中易网

springmvc 文件下载报错 getOutputStream() has already been called for this response

答案:1  悬赏:40  
解决时间 2021-02-16 05:17
public void download(String filePath,HttpServletResponse response){
try {
File file = new File(filePath);
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);//得到文件名
response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
String len = String.valueOf(file.length());
response.setHeader("Content-Length", len);//设置内容长度
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while((n=in.read(b))!=-1){
out.write(b, 0, n);
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
使用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;
}

}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
ups internal fault问题怎么解决
在升c大调中重升c演奏为升c时,其变音记号是
EXO2014年到现在参加过的所有颁奖典礼???
淘宝如何使用国际信用卡支付?
唐山高科总部大厦员工待遇怎么样
如图,用一块长方形铁板做一个圆柱形带盖的水
ケーキを食べることが好きだ。(我)喜欢吃蛋
嘉利冰淇淋店我想知道这个在什么地方
言之凿凿,更盼行之灼灼".怎么读
请问网上买橡木地板可靠吗?看了下价格都是20
跪求香奈儿普雷斯顿的古墓丽影种子
现在地球的科技树是不是已经点歪了
除了周德东还有那些优秀的恐怖小说家。
我想知道现在男女戴戒指有什么说法没有比如结
毛坯房地面上一条条平行的线条是什么
推荐资讯
韩国萨德与高中政治的相关
夏天要穿什么袜子比较凉爽?
两岁宝宝牙齿有虫洞,说牙齿疼,该怎么办
2016年上海哪些区初三物理有三模
国内最长超过历史记录的火车车厢达到多少节?
水浒q传装备耐久
王者荣耀里面开房间模式拿的五杀记入统计吗
用哭字写个字谜
梦见自己给死去的爷爷上坟却怎么也找不到墓地
|a-b|+|b-c|-|c-a|+|b+c|
花园桥地址有知道的么?有点事想过去
在JSP中怎么实现多项选择题,可以给以下源代码
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?