Esempio n. 1
0
  @Override
  public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
      throws IOException {
    if (!REQ_TYPE.equals(req.getContentType())) {
      rsp.sendError(SC_UNSUPPORTED_MEDIA_TYPE);
      return;
    }

    final Repository db = getRepository(req);
    try {
      final UploadPack up = uploadPackFactory.create(req, db);
      up.setBiDirectionalPipe(false);
      rsp.setContentType(RSP_TYPE);

      final SmartOutputStream out = new SmartOutputStream(req, rsp);
      up.upload(getInputStream(req), out, null);
      out.close();

    } catch (ServiceNotAuthorizedException e) {
      rsp.reset();
      rsp.sendError(SC_UNAUTHORIZED);
      return;

    } catch (ServiceNotEnabledException e) {
      rsp.reset();
      rsp.sendError(SC_FORBIDDEN);
      return;

    } catch (IOException e) {
      getServletContext().log("Internal error during upload-pack", e);
      rsp.reset();
      rsp.sendError(SC_INTERNAL_SERVER_ERROR);
      return;
    }
  }
Esempio n. 2
0
  /**
   * @param list 数据源
   * @param fieldMap 类的英文属性和Excel中的中文列名的对应关系
   * @param sheetName 工作表的名称
   * @param sheetSize 每个工作表中记录的最大个数
   * @param response 使用response可以导出到浏览器
   * @throws ExcelException @MethodName : listToExcel @Description : 导出Excel(导出到浏览器,可以自定义工作表的大小)
   */
  public static <T> void listToExcel(
      List<T> list,
      LinkedHashMap<String, String> fieldMap,
      String sheetName,
      int sheetSize,
      HttpServletResponse response)
      throws ExcelException {
    // 文件名默认设置为当前时间:年月日时分秒
    String fileName = DateFormatUtils.format(new Date(), "yyyyMMddhhmmss");
    // 设置response头信息
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");

    // 创建工作簿并发送到浏览器
    try {
      OutputStream os = response.getOutputStream();
      listToExcel(list, fieldMap, sheetName, sheetSize, os);
    } catch (Exception e) {
      e.printStackTrace();

      // 如果是ExcelException,则直接抛出
      if (e instanceof ExcelException) {
        throw (ExcelException) e;
      } else {
        // 否则将其他异常包装成ExcelException再抛出
        throw new ExcelException("导出excel失败");
      }
    }
  }
Esempio n. 3
0
  /**
   * @param response 相应客户端对象
   * @param fileName 下载文件的名称
   * @param filePath 下载文件的路径
   * @param old
   * @return boolean
   * @throws Exception
   */
  public static boolean download(
      HttpServletResponse response, String fileName, String filePath, String old) throws Exception {
    boolean flag = false;
    File file = new File(filePath); //
    System.out.println("--file_path:--" + filePath + "\\" + fileName);
    if (file.exists()) {

      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      byte[] buffer = new byte[1];
      response.reset();
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/x-rar-compressed");
      old =
          URLEncoder.encode(old, "UTF-8").replace("+", "%20").length() > 100
              ? URLEncoder.encode(old, "UTF-8").replace("+", "%20").substring(0, 100)
                  + "."
                  + old.substring(old.lastIndexOf(".") + 1)
              : URLEncoder.encode(old, "UTF-8").replace("+", "%20");
      response.setHeader("Content-disposition", "attachment;filename=" + old);
      OutputStream os = response.getOutputStream();
      while (bis.read(buffer) > 0) {
        os.write(buffer);
      }
      bis.close();
      os.close();
      flag = true;
    }
    return flag;
  }
Esempio n. 4
0
 /**
  * Download file entry of given path.
  *
  * @param user current user
  * @param path user
  * @param response response
  */
 @RequestMapping("/download/**")
 public void download(User user, @RemainedPath String path, HttpServletResponse response) {
   FileEntry fileEntry = fileEntryService.getFileEntry(user, path);
   if (fileEntry == null) {
     LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
     return;
   }
   response.reset();
   try {
     response.addHeader(
         "Content-Disposition",
         "attachment;filename="
             + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
   } catch (UnsupportedEncodingException e1) {
     LOG.error(e1.getMessage(), e1);
   }
   response.setContentType("application/octet-stream; charset=UTF-8");
   response.addHeader("Content-Length", "" + fileEntry.getFileSize());
   byte[] buffer = new byte[4096];
   ByteArrayInputStream fis = null;
   OutputStream toClient = null;
   try {
     fis = new ByteArrayInputStream(fileEntry.getContentBytes());
     toClient = new BufferedOutputStream(response.getOutputStream());
     int readLength;
     while (((readLength = fis.read(buffer)) != -1)) {
       toClient.write(buffer, 0, readLength);
     }
   } catch (IOException e) {
     throw new NGrinderRuntimeException("error while download file", e);
   } finally {
     IOUtils.closeQuietly(fis);
     IOUtils.closeQuietly(toClient);
   }
 }
Esempio n. 5
0
 public static void downLoad(
     HttpServletRequest request, HttpServletResponse response, String fileName, InputStream is) {
   OutputStream os = null;
   try {
     int length = is.available();
     byte b[] = new byte[length];
     is.read(b);
     // 清空response
     response.reset();
     response.setContentType("application/octet-stream"); // 设置为下载application/x-download
     response.setCharacterEncoding("UTF-8");
     response.setHeader(
         "Content-Disposition",
         "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); // 这个很重要
     response.addHeader("Content-Length", "" + length);
     os = new BufferedOutputStream(response.getOutputStream());
     os.write(b);
     os.flush();
   } catch (Exception e) {
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException e) {
       }
     }
     if (os != null) {
       try {
         os.close();
       } catch (IOException e) {
       }
     }
   }
 }
 private void handleDownload(File file) throws Exception {
   if (file.exists()) {
     HttpServletResponse response = this.context.getResponse();
     String filename = URLEncoder.encode(file.getName(), "utf-8");
     response.reset();
     response.setContentType("application/x-msdownload");
     response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
     int fileLength = (int) file.length();
     response.setContentLength(fileLength);
     /*如果文件长度大于0*/
     if (fileLength != 0) {
       /*创建输入流*/
       InputStream inStream = new FileInputStream(file);
       byte[] buf = new byte[4096];
       /*创建输出流*/
       ServletOutputStream servletOS = response.getOutputStream();
       int readLength;
       while (((readLength = inStream.read(buf)) != -1)) {
         servletOS.write(buf, 0, readLength);
       }
       inStream.close();
       servletOS.flush();
       servletOS.close();
     }
   }
 }
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
Esempio n. 8
0
 @Override
 protected void renderMergedOutputModel(
     Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   response.reset();
   response.setContentType(getContentType());
   response.setCharacterEncoding(characterEncoding);
   //
   Object bean = model.get(KEY_BEAN_DATA);
   if (bean == null) {
     bean = request.getAttribute(KEY_BEAN_DATA);
   }
   if (bean == null) {
     bean = model;
   }
   String type = this.determineReqType(request, model);
   if (TYPE_REQ_JSON.equalsIgnoreCase(type)) {
     jsonObj.writeValue(response.getWriter(), fix(bean));
   } else if (TYPE_REQ_XML.equalsIgnoreCase(type)) {
     log.error("The 'xml' type for response has not been implemented!");
     throw new RuntimeException("The 'xml' type for response has not been implemented!");
   } else {
     log.error("It is not support type of " + type + " for response !");
     throw new RuntimeException("It is not support type of " + type + " for response !");
   }
 }
Esempio n. 9
0
 /**
  * 输出到客户端
  *
  * @param fileName 输出文件名
  */
 public ExportExcel write(HttpServletResponse response, String fileName) throws IOException {
   response.reset();
   response.setContentType("application/octet-stream; charset=utf-8");
   response.setHeader(
       "Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
   write(response.getOutputStream());
   return this;
 }
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String tempFolderName = req.getParameter("tempFolderName");
    logger.debug("tempFolderName:" + tempFolderName);

    String filePath = this.getServletConfig().getServletContext().getRealPath("/");
    filePath +=
        Constant.FOLDER
            + File.separator
            + tempFolderName
            + File.separator
            + tempFolderName
            + ".zip";

    File zip = new File(filePath);
    if (zip.exists()) {

      String filename = URLEncoder.encode(zip.getName(), enc);
      resp.reset();
      resp.setContentType(contentType);
      resp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
      int fileLength = (int) zip.length();
      resp.setContentLength(fileLength);

      if (fileLength != 0) {
        /* 创建输入流 */
        InputStream inStream = null;
        ServletOutputStream out = null;
        try {
          inStream = new FileInputStream(zip);
          byte[] buf = new byte[4096];
          /* 创建输出流 */
          out = resp.getOutputStream();
          int readLength;
          while (((readLength = inStream.read(buf)) != -1)) {
            out.write(buf, 0, readLength);
          }
          out.flush();
        } catch (Exception e) {
          logger.error(e);
        } finally {
          if (null != out) {
            out.close();
          }
          if (null != inStream) {
            inStream.close();
          }
        }
      }

    } else {
      logger.error("zip包【" + zip.getPath() + "】不存在!");
    }

    logger.debug("下载的文件名【" + filePath + "】");

    // req.getRequestDispatcher("/listExcelServlet").forward(req, resp);
  }
Esempio n. 11
0
 private static void sendError(HttpServletResponse response, Response.Status status, String error)
     throws IOException {
   response.reset();
   response.setStatus(status.getStatusCode());
   response.setContentType(MediaType.TEXT_PLAIN);
   PrintWriter writer = response.getWriter();
   writer.println(error);
   writer.close();
 }
Esempio n. 12
0
 private String writerMessageToClient(HttpServletResponse response, String message)
     throws IOException {
   response.reset();
   response.setContentType("text/plain;charset=UTF-8");
   PrintWriter writer = response.getWriter();
   writer.append(message.replaceAll("null", "").replaceAll("\r\n", " "));
   writer.close();
   return null;
 }
Esempio n. 13
0
 /**
  * 导出系统
  *
  * @return
  * @throws Exception
  */
 public String exportFuncGroup() throws Exception {
   HttpServletResponse response = ServletActionContext.getResponse();
   response.reset();
   response.setContentType("application/x-download");
   response.addHeader(
       "Content-Disposition",
       "attachment;filename=" + URLEncoder.encode("acs-func-group.xls", "UTF-8"));
   dataHandle.exportFunGroup(response.getOutputStream(), systemId, funcGroupIds);
   return null;
 }
Esempio n. 14
0
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   HttpServletRequest httpRequest = maybeAppendHtmlToPath(request);
   HttpServletResponse httpResponse = (HttpServletResponse) response;
   ResponseStatusCapture capture = new ResponseStatusCapture(httpResponse);
   chain.doFilter(httpRequest, capture);
   if (capture.isError()) {
     httpResponse.reset();
     request.setAttribute(RackDispatcher.DYNAMIC_REQS_ONLY, Boolean.TRUE);
     dispatcher.process((HttpServletRequest) request, httpResponse);
   }
 }
Esempio n. 15
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String imagesPath = applicationConfiguration.getImagesPath();

    // get itemId parameter from request
    String imageName = request.getParameter("name");
    if (imageName == null) {
      return;
    }

    File imageFile = new File(imagesPath, imageName);

    if (imageFile.exists()) {
      // determine the content type of file - if it's not an image quit
      String contentType = getServletContext().getMimeType(imageFile.getName().toLowerCase());
      if (contentType == null || !contentType.startsWith("image")) {
        return;
      }

      // init servlet response
      response.reset();
      response.setBufferSize(DEFAULT_BUFFER_SIZE);
      response.setHeader("Content-Type", contentType);
      response.setHeader("Content-Length", String.valueOf(imageFile.length()));
      response.setHeader("Content-Disposition", "inline; filename=\"" + imageFile.getName() + "\"");

      long expiry = new Date().getTime() + CACHE_AGE * 1000;
      response.setDateHeader("Expires", expiry);
      response.setHeader("Cache-Control", "max-age=" + CACHE_AGE);

      // prepare streams
      BufferedInputStream input = null;
      BufferedOutputStream output = null;

      try {
        // open streams
        input = new BufferedInputStream(new FileInputStream(imageFile), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
        // write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
          output.write(buffer, 0, length);
        }
        // finalize task
        output.flush();
      } finally {
        // close streams
        output.close();
        input.close();
      }
    }
  }
Esempio n. 16
0
 /**
  * 客户端返回字符串
  *
  * @param response
  * @param string
  * @return
  */
 protected String renderString(HttpServletResponse response, String string, String type) {
   try {
     response.reset();
     response.setContentType(type);
     response.setCharacterEncoding("utf-8");
     response.getWriter().print(string);
     return null;
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
 }
Esempio n. 17
0
  /**
   * Peticion para exportar las etiquetas pendientes de generar
   *
   * @param request Peticion
   * @param response Respuesta
   * @return Componente tile al que se redirige (si es correcta la generación del pdf se devuelve
   *     null)
   */
  @RequestMapping(value = "/persona/etiquetasPendientes")
  public String etiquetasPendientes(HttpServletRequest request, HttpServletResponse response) {

    // Generar el informe en formato Excel
    PersonaQueryBean personaQueryBean =
        (PersonaQueryBean) request.getSession().getAttribute("personaQueryBean");

    String username = (String) SecurityAccess.getUserInformation().getUsername();

    String reportName = "etiquetasPersonasReport";
    String reportTitle =
        this.messageSource.getMessage("page.breadcrumb.persona", null, WebCoreUtils.getLocale());
    String reportType = "PDF";
    String fullReportName = null;
    String contentType = null;

    Boolean vacio = false;

    try {
      fullReportName = "etiquetasPendientesReport.pdf";
      contentType = "application/pdf";

      byte[] byteArray =
          this.personaService.etiquetasPersonas(
              username, personaQueryBean, reportType, reportName, reportTitle);
      if (byteArray == null) {
        vacio = true;
      } else {
        response.reset();
        response.setContentType(contentType);
        response.setHeader(
            "Content-disposition", "attachment" + ";filename=\"" + fullReportName + "\"");
        response.addHeader("Pragma", "no cache");
        response.addHeader("Cache-control", "private, must-revalidate");

        ServletOutputStream outstream = response.getOutputStream();
        outstream.write(byteArray);
        outstream.flush();
        outstream.close();
      }
    } catch (IOException e) {
      LOGGER.error(e.getMessage());
      return "app/errorEtiquetas";
    }

    if (vacio) {
      LOGGER.info("No hay registros");
      return "app/sinEtiquetas";
    }

    return null;
  }
  /**
   * This method will open the sample report pdf.
   *
   * @param reportFilePath - full path of the sample report to be shown.
   * @param request - instance of HttpServletRequest
   * @param response - instance of HttpServletResponse
   * @throws ServletException - error
   * @throws IOException - error
   */
  private static void showSampleReport(
      String reportFilePath, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (null != request.getSession().getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
        && request
            .getSession()
            .getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT)
            .toString()
            .equalsIgnoreCase("Y")) {
      ServletOutputStream output = null;
      try {

        FileInputStream fis = new FileInputStream(reportFilePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[256];
        try {
          for (int readNum; (readNum = fis.read(buf)) != -1; ) {
            baos.write(buf, 0, readNum); // no doubt here is 0
            // Writes len bytes from the specified byte array starting at offset off to this byte
            // array output stream.
          }

        } catch (IOException ex) {
          ex.printStackTrace();
        }

        if (null != baos) {

          // Init servlet response.
          response.reset();
          response.setContentType("application/pdf");
          response.setContentLength(baos.size());
          response.setHeader("Content-disposition", "inline; filename=\"" + reportFilePath);
          response.setHeader("Expires", "0");
          response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
          //                  response.setHeader("Transfer-Encoding", "identity");
          output = response.getOutputStream();

          output.write(baos.toByteArray(), 0, baos.size());

          // Finalize task.
          output.flush();
        }
      } catch (Exception exception) {
        OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception);
      } finally {

        // Gently close streams.
        close((Closeable) output);
      }
    }
  }
Esempio n. 19
0
  @SuppressWarnings("unchecked")
  public static void downLoad(
      List downList, String fileName, HttpServletResponse httpResponse, String downLoadId) {
    // 获取列对象集合
    httpResponse.reset();
    List columnList = new ArrayList();
    try {
      // 初始化参数
      DownloadBean downloadBean = DownloadContentHelper.getDownloadBean(downLoadId);
      columnList = downloadBean.getAttributes();
    } catch (Exception e) {

    }
    OutputStream output = null;
    try {
      output = httpResponse.getOutputStream();
      httpResponse.setContentType("application/vnd.ms-excel; charset=GBK");
      httpResponse.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
      WritableWorkbook w = Workbook.createWorkbook(output);
      output.flush();
      // 分sheet页操作start
      List<Object> newTotals = new ArrayList<Object>();
      Iterator itTotals = downList.iterator();
      while (itTotals.hasNext()) {
        newTotals.add(itTotals.next());
      }
      int sheetNum = 0;
      while (newTotals.size() > MisConstants.MAXNUM_FOR_PER_SHEET) {
        WritableSheet ws = w.createSheet("Page" + (sheetNum + 1), sheetNum);
        addLabelExcel(ws, newTotals.subList(0, MisConstants.MAXNUM_FOR_PER_SHEET), columnList);
        newTotals.subList(0, MisConstants.MAXNUM_FOR_PER_SHEET).clear();
        sheetNum = sheetNum + 1;
      }
      WritableSheet ws = w.createSheet("Page" + (sheetNum + 1), sheetNum);
      addLabelExcel(ws, newTotals, columnList);
      // 分sheet页操作end
      w.write();
      // 关闭Excel工作薄对象
      w.close();
      if (output != null) output.close();

    } catch (Exception e) {
      if (output != null)
        try {
          output.close();
        } catch (IOException e1) {
        }
      e.printStackTrace();
    }
  }
Esempio n. 20
0
  public static void ResponseXls(
      HttpServletResponse response, List<List<String>> xlsList, String filePath) {
    // Stream
    OutputStream out = null;
    Workbook wb = null;
    WritableWorkbook book = null;
    try {
      out = response.getOutputStream();
      // 工作本
      if (filePath == null) {
        book = Workbook.createWorkbook(out);
        book.createSheet(SHEET_DEFAULT_NAME, 0);
      } else {
        wb = Workbook.getWorkbook(new File(filePath));
        book = Workbook.createWorkbook(out, wb);
      }
      /*
       * 检查 如果fieldsList为空,则读取工作表获得
       */
      WritableSheet sheet = book.getSheet(0);
      CreateXlsSheet(sheet, xlsList);
      response.reset();
      response.addHeader(
          "Content-Disposition",
          "attachment;filename="
              + (filePath == null ? String.format("%tF", new Date()) + ".xls" : filePath));
      response.setContentType("application/octet-stream");

      book.write();
      book.close();
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
      // 关闭流对象
    } finally {
      try {
        if (book != null) book.close();
      } catch (Exception e) {
      }
      try {
        if (wb != null) wb.close();
      } catch (Exception e) {
      }
      try {
        if (out != null) out.close();
      } catch (Exception e) {
      }
    }
  }
Esempio n. 21
0
  protected void downloadFile(HttpServletResponse response, File file, String contentType)
      throws IOException {
    String fileName = file.getName();
    response.reset();
    HttpServletRequest request = this.getRequest();
    response.setContentType(contentType);
    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) { // IE
      // 设置文件头,文件名称或编码格式
      response.addHeader(
          "Content-Disposition",
          "attachment;filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");
    } else { // firefox
      response.addHeader(
          "Content-Disposition",
          "attachment;filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
    }

    OutputStream myout = null;
    FileInputStream fis = null;
    try {
      // 读出文件到i/o流
      fis = new FileInputStream(file);
      BufferedInputStream buff = new BufferedInputStream(fis);
      byte[] b = new byte[1024]; // 相当于我们的缓存
      long k = 0; // 该值用于计算当前实际下载了多少字节
      // 从response对象中得到输出流,准备下载
      myout = response.getOutputStream();
      // 开始循环下载
      while (k < file.length()) {
        int j = buff.read(b, 0, 1024);
        k += j;
        // 将b中的数据写到客户端的内存
        myout.write(b, 0, j);
      }
      if (buff != null) {
        buff.close();
      }
    } finally {
      if (myout != null) {
        myout.close();
      }
      if (fis != null) {
        fis.close();
      }
    }
  }
Esempio n. 22
0
  /**
   * 使用 xls模板导出
   *
   * @param response
   * @param xlsList
   * @param templatePath
   */
  public void abstractResponseXls(HttpServletResponse response, String filePath, String downName) {
    // Stream
    OutputStream out = null;
    Workbook wb = null;
    WritableWorkbook book = null;
    try {
      out = response.getOutputStream();
      // 工作本
      if (filePath == null) {
        book = Workbook.createWorkbook(out);
        book.createSheet(SHEET_DEFAULT_NAME, 0);
      } else {
        System.out.println("使用模板:" + filePath);
        wb = Workbook.getWorkbook(new File(filePath));
        book = Workbook.createWorkbook(out, wb);
      }
      /*
       * 检查 如果fieldsList为空,则读取工作表获得
       */
      this.abstractCreateXlsSheet(book);
      response.reset();
      response.addHeader("Content-Disposition", "attachment;filename=" + downName);
      response.setContentType("application/octet-stream");

      book.write();
      book.close();
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
      // 关闭流对象
    } finally {
      try {
        if (book != null) book.close();
      } catch (Exception e) {
      }
      try {
        if (wb != null) wb.close();
      } catch (Exception e) {
      }
      try {
        if (out != null) out.close();
      } catch (Exception e) {
      }
    }
  }
Esempio n. 23
0
  /**
   * 使用http请求下载附件。
   *
   * @param sourceFilePath 导出文件路径
   * @param exportName 导出名字
   */
  public static void downloadFileByHttp(HttpServletResponse response, String sourceFilePath) {
    File sourceFile = new File(sourceFilePath);
    if (!sourceFile.exists()) {
      log.error("下载附件时,发现文件【" + sourceFilePath + "】不存在");
      return;
    }

    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/octet-stream"); // 设置附件类型
    response.setContentLength((int) sourceFile.length());
    response.setHeader(
        "Content-Disposition",
        "attachment; filename=\"" + EasyUtils.toUtf8String(sourceFile.getName()) + "\"");

    InputStream inStream = null;
    OutputStream outStream = null;
    try {
      outStream = response.getOutputStream();
      inStream = new FileInputStream(sourceFilePath);

      int len = 0;
      byte[] b = new byte[1024];
      while ((len = inStream.read(b)) != -1) {
        outStream.write(b, 0, len);
        outStream.flush();
      }
    } catch (IOException e) {
      throw new BusinessException("导出时发生IO异常!", e);
    } finally {
      sourceFile.delete(); // 删除导出目录下面的临时文件

      try {
        if (inStream != null) {
          inStream.close();
        }
        if (outStream != null) {
          outStream.close();
        }
      } catch (IOException e) {
        throw new RuntimeException("导出完成后关闭流时发生IO异常", e);
      }
    }
  }
Esempio n. 24
0
  public void download(HttpServletResponse response, String filename) throws IOException {
    StringTokenizer tokenTO = new StringTokenizer(filename, "\\");
    int j = 0;
    String[] filepath1 = new String[10];
    while (tokenTO.hasMoreTokens()) {
      filepath1[j] = tokenTO.nextToken();
      j++;
    }
    String filepath = "";
    for (int m = 0; m < j - 1; m++) {
      filepath = filepath + filepath1[m] + "\\";
    }
    filepath = filepath + filepath1[j - 1];
    File down_file = new java.io.File(filepath);
    long l = down_file.length(); // 文件长度
    InputStream in = new FileInputStream(down_file);

    if (in != null) {
      try {
        String fs = down_file.getName();
        response.reset();
        response.setContentType(null); //
        String s = "attachment; filename=" + fs; //
        response.setHeader("Content-Disposition", s); // 以上输出文件元信息

        OutputStream output = null;
        FileInputStream fis = null;

        output = response.getOutputStream();
        fis = new FileInputStream(filepath);
        response.setContentLength((int) l);
        byte[] b = new byte[2048];
        int i = 0;
        while ((i = fis.read(b)) > 0) {
          output.write(b, 0, i);
        }
        output.flush();
        in.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 25
0
  /**
   * Peticion para exportar la etiqueta de una persona
   *
   * @param request Peticion
   * @param response Respuesta
   * @return Componente tile al que se redirige (si es correcta la generación del pdf se devuelve
   *     null)
   */
  @RequestMapping(value = "/persona/etiquetaPersona")
  public String etiquetaPersona(HttpServletRequest request, HttpServletResponse response) {

    // Generar el informe en formato Excel
    PersonaQueryBean personaQueryBean = new PersonaQueryBean();
    String idPersona = (String) RequestUtil.getStringParameter(request, "idPersona");
    personaQueryBean.setIdPersona(Long.valueOf(idPersona));

    String username = (String) SecurityAccess.getUserInformation().getUsername();
    String reportName = "etiquetasPersonasReport";
    String reportTitle =
        this.messageSource.getMessage("page.breadcrumb.persona", null, WebCoreUtils.getLocale());
    String reportType = "PDF";
    String fullReportName = null;
    String contentType = null;

    try {

      fullReportName = "etiquetaPersonaReport.pdf";
      contentType = "application/pdf";

      byte[] byteArray =
          this.personaService.etiquetaPersona(
              username, personaQueryBean, reportType, reportName, reportTitle);

      response.reset();
      response.setContentType(contentType);
      response.setHeader(
          "Content-disposition", "attachment" + ";filename=\"" + fullReportName + "\"");
      response.addHeader("Pragma", "no cache");
      response.addHeader("Cache-control", "private, must-revalidate");

      ServletOutputStream outstream = response.getOutputStream();
      outstream.write(byteArray);
      outstream.flush();
      outstream.close();
    } catch (IOException e) {
      LOGGER.error(e.getMessage());
      return "app/errorPage";
    }

    return null;
  }
Esempio n. 26
0
 public String rctj() {
   try {
     String url = getRealPath("file/123.xls");
     String fname = new Date().getTime() + ".xls";
     File file = new File(fname);
     FileInputStream in = new FileInputStream(url);
     FileOutputStream fos = new FileOutputStream(file);
     byte[] buf = new byte[1024];
     int c;
     while ((c = in.read(buf)) != -1) {
       fos.write(buf, 0, c);
     }
     in.close();
     fos.close();
     HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
     HSSFSheet sheet = workbook.getSheetAt(0);
     for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
       HSSFRow row = sheet.getRow(rowIndex);
       if (row != null) {
         for (int i = 0; i < row.getRowNum(); i++) {
           System.out.println(getCellString(row.getCell(i)));
         }
       }
     }
     HttpServletResponse response = getResponse();
     OutputStream os = response.getOutputStream(); // 取得输出流
     response.reset(); // 清空输出流
     String n = "321.xls";
     String name = new String(n.getBytes("GB2312"), "ISO8859-1");
     response.setHeader(
         "Content-disposition", "attachment; filename=\"" + name + "\""); // 设定输出文件头
     response.setContentType("application/msexcel"); // 定义输出类型
     workbook.write(os); // 写入文件
     os.close(); // 关闭流
     if (file.exists()) {
       file.delete();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return this.NONE;
 }
Esempio n. 27
0
 /** 文件下载 */
 public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
   try {
     // 获取下载文件路径
     String path =
         request.getSession().getServletContext().getRealPath("magazines")
             + File.separator
             + request.getParameter("file");
     // 编码
     path = URLEncoder.encode(path, "ISO-8859-1");
     // 解码
     path = URLDecoder.decode(path, "UTF-8");
     File file = new File(path);
     // 文件名
     String fileName = file.getName();
     // 扩展名
     @SuppressWarnings("unused")
     String ext =
         fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toUpperCase();
     // 输入流
     InputStream inStream = new FileInputStream(path);
     InputStream in = new BufferedInputStream(inStream);
     byte[] bs = new byte[in.available()];
     in.read(bs);
     in.close();
     // 清空response
     response.reset();
     // 设置response的Header
     // 使浏览器弹出下载对话框
     response.addHeader(
         "Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
     response.addHeader("Content-Length", "" + file.length());
     // 输出流
     OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
     response.setContentType("application/octet-stream");
     toClient.write(bs);
     toClient.flush();
     toClient.close();
   } catch (Exception e) {
   }
   return "3:ajax";
 }
 // 2015-5-10导出花名册
 @RequestMapping(value = "/export", method = RequestMethod.GET)
 @ResponseBody
 public void export(
     Boolean inUse, HttpSession session, HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   String fileName = "花名册";
   // 填充projects数据
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   try {
     List<Employee> list = employeeService.getList(inUse); // 这个是从数据库中取得要导出的数据
     createEmployeesFile(list, os);
   } catch (IOException e) {
     throw e;
   }
   byte[] content = os.toByteArray();
   InputStream is = new ByteArrayInputStream(content);
   // 设置response参数,可以打开下载页面
   response.reset();
   response.setContentType("application/vnd.ms-excel;charset=utf-8");
   response.setHeader(
       "Content-Disposition",
       "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   try {
     bis = new BufferedInputStream(is);
     bos = new BufferedOutputStream(response.getOutputStream());
     byte[] buff = new byte[2048];
     int bytesRead;
     // Simple read/write loop.
     while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
       bos.write(buff, 0, bytesRead);
     }
   } catch (final IOException e) {
     throw e;
   } finally {
     if (bis != null) bis.close();
     if (bos != null) bos.close();
   }
 }
  static void returnOembed(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String url = request.getParameter("url");
    if (url == null) throw new Exception("No subject URL found.");

    String retUrl = request.getParameter(S3Servlet.URL_PARAM);
    if (retUrl == null && !S3Servlet.testing)
      throw new Exception("Recieved no launch presentation return url");

    Enumeration<String> en = request.getParameterNames();
    ArrayList<String> keys = new ArrayList<String>(), vals = new ArrayList<String>();

    String key, value;
    while (en.hasMoreElements()) {
      key = en.nextElement();
      if ("action".equals(key)) continue;
      if ("launch_presentation_return_url".equals(key)) continue;
      if ("url".equals(key)) continue;

      if ((value = request.getParameter(key)) != null) {
        keys.add(key);
        vals.add(value);
      } // if//
    } // while//

    String endpoint =
        S3Servlet.makeUrl(
            S3Servlet.server + S3Servlet.prefix + "/" + S3Action.oembed,
            keys.toArray(new String[keys.size()]),
            vals.toArray(new String[vals.size()]));

    String oembedUrl =
        S3Servlet.makeUrl(
            retUrl,
            new String[] {"embed_type", "endpoint", "url"},
            new String[] {"oembed", endpoint, url});

    response.reset();
    response.sendRedirect(oembedUrl);
  } // returnOembed//
Esempio n. 30
0
 public ActionForward expTemp(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   String filepath = this.servlet.getServletContext().getRealPath("template") + "/pjxs.xls";
   response.reset();
   response.setContentType("application/x-msdownload");
   response.addHeader("Content-Disposition", "attachment;filename=pjxs.xls");
   OutputStream output = response.getOutputStream();
   InputStream fis = new FileInputStream(filepath);
   byte[] b = new byte[1024];
   int i = 0;
   while ((i = fis.read(b)) > 0) {
     output.write(b, 0, i);
   }
   output.flush();
   fis.close();
   output.close();
   return null;
 }