最近搞一个微信公众号开发的下载功能;就是要从自己服务器上下载图片到手机上,下载没问题,用的spring mvc的下载,但是下载的时候图片过大的话还没下载完的话微信就会自动在发送链接,,导致报错。
就会调用三次方法导致返回错误。
018-01-23 10:24:24.446 [ERROR] [http-nio-8080-exec-6] o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/healthcarewechat] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:619)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:211)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:189)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1282)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
这种要怎么解决呢?
下载的也是这样实现
if(!file.exists()){
return;//文件不存在就退出方法
}
FileInputStream fileInputStream = new FileInputStream(file);
//设置Http响应头告诉浏览器下载这个附件
response.setContentType("image/jpeg");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream outputStream = response.getOutputStream();
byte[] bytes = new byte[2048];
int len = 0;
while ((len = fileInputStream.read(bytes))>0){
outputStream.write(bytes,0,len);
}
fileInputStream.close();
outputStream.close();