public void download(HttpServletRequest request, HttpServletResponse response, String fileName, byte[] content) { try { String fileNameUtf8 = URLEncoder.encode(fileName, "UTF8"); setResponseHeader(response, fileNameUtf8); response.getOutputStream().write(content, 0, content.length); } catch (Exception e) { logger.error(fileName + "-电子合同下载失败!", e); BusinessException.throwMessage(fileName + "-电子合同生成失败!" + e.getMessage()); } }
private void setResponseHeader(HttpServletResponse response, String fileName) { String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length()); String prefix = fileName.substring(0, fileName.lastIndexOf(".")); try { response.reset(); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(prefix.getBytes("GB2312"), "ISO8859-1") + suffix); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } }
public void download(HttpServletRequest request, HttpServletResponse response, String fileName, String html) { FileOutputStream fos = null; FileInputStream fis = null; File file = null; try { String path = request.getSession().getServletContext().getRealPath(File.separator) + UUID.randomUUID(); file = new File(path + ".pdf"); fos = new FileOutputStream(file); PdfUtil.createPdf(PdfUtil.contractHtmlHandle(html), fos, "fonts/simfang.ttf"); fis = new FileInputStream(file); byte[] buf = new byte[10240]; int length; String fileNameUtf8 = URLEncoder.encode(fileName, "UTF8"); setResponseHeader(response, fileNameUtf8); while (((length = fis.read(buf)) != -1)) { response.getOutputStream().write(buf, 0, length); } } catch (Exception e) { logger.error(fileName + "-电子合同下载失败!", e); logger.error(html); BusinessException.throwMessage(fileName + "-电子合同生成失败!" + e.getMessage()); } finally { try { if (fis != null) { fis.close(); } } catch (Exception e) { logger.error(e.getMessage()); } try { if (fos != null) { fos.close(); } } catch (Exception e) { logger.error(e.getMessage()); } if (file != null) { file.delete(); } } }