public static void downLoadFile(InputStream inStream, String fileName) { if (StringUtils.isBlank(fileName)) { fileName = UUID.randomUUID().toString().replaceAll("-", ""); } HttpServletRequest req = getRequest(); String agent = req.getHeader("User-Agent"); boolean isMSIE = (agent != null) && (agent.indexOf("MSIE") != -1); try { if (isMSIE) { fileName = URLEncoder.encode(fileName, "UTF-8"); fileName = fileName.replace("+", "%20"); } else { fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpServletResponse response = getResponse(); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment;filename="" + fileName + """); response.setContentType("application/octet-stream"); OutputStream outStream = null; try { outStream = response.getOutputStream(); byte[] cache = new byte[1024]; int length = inStream.read(cache); while (length != -1) { outStream.write(cache, 0, length); length = inStream.read(cache); } } catch (IOException e) { e.printStackTrace(); try { outStream.flush(); } catch (IOException e) { e.printStackTrace(); } try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } finally { try { outStream.flush(); } catch (IOException e) { e.printStackTrace(); } try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static HttpServletRequest getRequest() { ActionContext ac = ActionContext.getContext(); HttpServletRequest req = null; if (ac != null) { req = (HttpServletRequest)ac.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest"); } return req; }
public static HttpServletResponse getResponse() { ActionContext ac = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse)ac.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"); return response; }