コード例 #1
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse resp)
     throws ServletException, IOException {
   request.setCharacterEncoding("UTF-8");
   String FSP = System.getProperty("file.separator");
   String LSP = System.getProperty("line.separator");
   String url = "";
   JSONObject backJsonObejct = new JSONObject();
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   String result;
   String fileName = "";
   try {
     List items = upload.parseRequest(request);
     Iterator iter = items.iterator();
     while (iter.hasNext()) {
       // 把实体换成map,然后保存
       FileItem item = (FileItem) iter.next();
       if (!item.isFormField()) {
         fileName = item.getName();
         String appendix = "";
         int indexOfDot = fileName.lastIndexOf(".");
         if (indexOfDot >= 0) {
           appendix = fileName.substring(indexOfDot);
         }
         byte[] fileBytes = item.get();
         String systemFileName = "upload-" + System.currentTimeMillis() + appendix;
         String filePath = "upload" + FSP + systemFileName;
         String realPath = request.getRealPath(FSP) + filePath;
         String dirPath = request.getRealPath(FSP) + "upload";
         File uploadedFile = new File(dirPath);
         if (!uploadedFile.isDirectory()) {
           uploadedFile.mkdirs();
         }
         System.out.println(item.getFieldName() + ":" + fileName);
         uploadedFile = new File(realPath);
         item.write(uploadedFile);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   // 输出json
   PrintWriter pw = resp.getWriter();
   pw.append("{success:true}");
   pw.flush();
   pw.close();
 }
コード例 #2
0
ファイル: DownloadFileAction.java プロジェクト: Aras90/Evento
  public String execute() throws Exception {
    String filePath = servletRequest.getRealPath("/");
    System.out.println("Server path:" + filePath);
    fileInputStream = new FileInputStream(new File(filePath, "nowy.zip"));

    return SUCCESS;
  }
コード例 #3
0
 public void UploadFile(
     MultipartFile file, String name, String folder, HttpServletRequest request) {
   if (!file.isEmpty()) {
     try {
       String sp = File.separator;
       String pathname =
           request.getRealPath("")
               + "WEB-INF"
               + sp
               + "classes"
               + sp
               + "static"
               + sp
               + folder
               + sp
               + name;
       BufferedOutputStream stream =
           new BufferedOutputStream(new FileOutputStream(new File(pathname)));
       stream.write(file.getBytes());
       stream.close();
     } catch (FileNotFoundException e) {
     } catch (IOException e) {
     }
   }
 }
コード例 #4
0
 @RequestMapping(value = "/UploadFile.htm")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   File file = null;
   try {
     List<FileItem> items = upload.parseRequest(request);
     if (isMultipart) {
       for (FileItem item : items) {
         if (!item.isFormField()) {
           String name = new File(item.getName()).getName();
           file = new File(request.getRealPath(File.separator) + File.separator + name);
           item.write(file);
         }
       }
       readFileImpl.readCSVFile(file);
       request.getRequestDispatcher("jsp/display.jsp").forward(request, response);
     }
   } catch (FileUploadException e) {
     e.printStackTrace();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #5
0
 @SkipValidation
 public String addTool() {
   try {
     System.out.println("addTool");
     File f = new File("newFile.txt");
     f.createNewFile();
     logger.debug("addTool");
     toolBean.setManufacturer(manufacturer);
     toolBean.setName(name);
     toolBean.setUpload(upload);
     toolBean.setUploadFileName(manufacturer + "-" + uploadFileName);
     String filePath = req.getRealPath("/");
     logger.debug("Server Path = " + filePath);
     String fullFileName = filePath + "Uploads\\" + manufacturer + "-" + getUploadFileName();
     logger.debug("FullFileName = " + fullFileName);
     File theFile = new File(fullFileName);
     theFile.createNewFile();
     FileUtils.copyFile(toolBean.getUpload(), theFile);
     toolService.addTool(toolBean);
     addActionMessage("Insertion successful");
     return SUCCESS;
   } catch (Exception e) {
     addActionError("There was a problem while inserting tool information.Please Contact Admin");
     logger.error(e.getMessage(), e);
     return ERROR;
   }
 }
コード例 #6
0
 public Map upload(HttpServletRequest request, FileItem item) {
   Map mapList = new HashMap();
   try {
     if (item.isFormField()) {
       // 普通表单
     } else {
       String fieldName = item.getFieldName();
       String fileName = item.getName();
       // 如果文件域没有填写内容,或者填写的文件不存在
       if ("".equals(fileName) || item.getSize() == 0) {
         return mapList;
       }
       String userfilepath = request.getRealPath("upload");
       String date = "/" + fnu.getDate8() + "/";
       String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
       String newfilename = fnu.getUUID() + "." + extName;
       File uploadedFile = new File(userfilepath + date + newfilename);
       if (!uploadedFile.exists()) { // 如果要写入的文件或目录不存在,那么试着创建要写入的目录,以便写入文件
         uploadedFile.getParentFile().mkdirs();
       }
       item.write(uploadedFile);
       mapList.put("fieldname", fieldName);
       mapList.put(
           "filename",
           fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()));
       mapList.put("extname", extName);
       mapList.put("filepath", userfilepath + date + newfilename);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return mapList;
 }
コード例 #7
0
  public CopyOfExportTask(
      String connectUrls,
      String queryProcedure,
      Map<String, String> params,
      String resultProcedure,
      HttpServletRequest request) {
    this.connectUrls = connectUrls;

    this.params = new HashMap<String, String>();
    Object[] keys = params.keySet().toArray();
    this.keys = new String[keys.length];
    for (int i = 0; i < keys.length; i++) { // 把map里所有key转成小写,与执行的存储过程保持一致
      String key = keys[i].toString();
      this.keys[i] = key.toLowerCase();
      this.params.put(key.toLowerCase(), MapUtils.getString(params, key, ""));
    }
    this.queryProcedure = handleSql(queryProcedure.toLowerCase(), this.params);
    this.resultProcedure = resultProcedure.toLowerCase();
    this.fileName =
        MapUtils.getString(params, "modulename", "导出文件")
            + "_"
            + new SimpleDateFormat(Constant.TIMESTAMP_FORMAT_yyyyMMddHHmmssSSS).format(new Date())
            + Constant.EXCEL;
    this.ip = request.getServerName();
    this.port = request.getServerPort();
    this.filePath =
        request.getRealPath(Constant.EXPORT_PATH_FOLDER) + File.separatorChar + this.fileName;
    this.jt = DBUtil.getReadJdbcTemplate(this.connectUrls);
  }
コード例 #8
0
  @SuppressWarnings("deprecation")
  @RequestMapping(params = "method=getfilepath")
  public void getExpFilePath(HttpServletRequest request, HttpServletResponse response) {
    String filePath = "";

    String description = request.getParameter("description");

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("description", description);

    List<MobileAppConfig> list = mobileAppConfigService.findForUnPage(params);

    if (list.size() > 0) {
      try {
        String path = request.getRealPath("/") + "userfile\\xls";

        filePath = mobileAppConfigService.ExpExcel(list, path);

      } catch (Exception e) {
        // TODO: handle exception
        System.out.print(e.getMessage());
      }
    }

    try {
      filePath = response.encodeURL(filePath);
      response.getWriter().write(filePath);
    } catch (Exception e) {
      // TODO: handle exception
      System.out.print(e.getMessage());
    }
  }
コード例 #9
0
  @RequestMapping(value = "/ViewReports", method = RequestMethod.POST)
  public String prs(
      ModelMap model,
      HttpServletRequest request,
      HttpServletResponse response,
      @Valid CompanyReports CompanyName,
      BindingResult result) {

    if (result.hasErrors()) {
      System.out.println("sa");
      model.addAttribute("up", "Please Check the Values Entered");
      model.addAttribute("StockSearchHelper", new stocksearchhelper());
      model.addAttribute("CompanyName", new CompanyReports());
      List<stock> x = stockServiceInterface.liststock("NASDAQ");
      List<stock> y = stockServiceInterface.liststock("NASDAQCOMPOSITE");
      List<stock> z = stockServiceInterface.liststock("DOWJONES");
      List<stock> a = stockServiceInterface.liststock("GOLD");
      List<stock> b = stockServiceInterface.liststock("SANDP");
      List<stock> c = stockServiceInterface.liststock("OIL");
      model.addAttribute("NASDAQ", x.get(0).getPrice());
      model.addAttribute("NASDAQCOMPOSITE", y.get(0).getPrice());
      model.addAttribute("DOWJONES", z.get(0).getPrice());
      model.addAttribute("GOLD", a.get(0).getPrice());
      model.addAttribute("SANDP", b.get(0).getPrice());
      model.addAttribute("OIL", c.get(0).getPrice());
      List<TopPerformers> opds1 = topPerformerServiceInterface.liststock();
      model.addAttribute("first", opds1.get(0).getTickerCode());
      model.addAttribute("second", opds1.get(1).getTickerCode());
      model.addAttribute("third", opds1.get(2).getTickerCode());
      model.addAttribute("fourth", opds1.get(3).getTickerCode());
      return "ClientHome";
    } else {

      System.out.println("saa");
      String cn = CompanyName.getCompanyName();

      // String
      // s="C:"+File.separator+"Users"+File.separator+"nisha"+File.separator+"Desktop"+File.separator+"New folder (6)"+File.separator+".metadata"+File.separator+".plugins"+File.separator+"org.eclipse.wst.server.core"+File.separator+"tmp1"+File.separator+"wtpwebapps"+File.separator+"Project"+File.separator+"images"+File.separator;

      String s = request.getRealPath("") + File.separator;

      String e = s + CompanyName.getCompanyName() + ".pdf";
      File files = new File(e);

      response.setContentType("application/pdf"); // in my example this was an xls file
      response.setContentLength(new Long(files.length()).intValue());
      response.setHeader("Content-Disposition", "attachment; filename=MyFile.pdf");

      try {
        FileCopyUtils.copy(new FileInputStream(files), response.getOutputStream());
      } catch (IOException es) {
        es.printStackTrace();
      }

      // return "redirect:/Client/viewmyaccount";

      return "redirect:/success";
    }
  }
コード例 #10
0
  public Map EmployeeFundsUpEPFFormDBFPrintout(
      String year,
      String month,
      String empcategory,
      HttpServletRequest request,
      HttpServletResponse response) {
    Map map = new HashMap();
    try {
      //            String fileName = null;
      //            fileName = "Depf" + months[Integer.valueOf(month) - 1] + year.substring(2, 4) +
      // ".txt";
      String fileName =
          reportNameService.getFileName(
              null, request, response, null, null, empcategory + "", month, year);
      String rcode = fileName.substring(1, 3);
      fileName =
          empcategory
              + ""
              + rcode
              + ""
              + months[Integer.valueOf(month) - 1]
              + year.substring(2, 4)
              + ".txt";
      OeslModule notOnWeekendsModule = new OeslModule();
      Injector injector = Guice.createInjector(notOnWeekendsModule);

      EmployeeFundSubService employeeFundSubService =
          (EmployeeFundSubService) injector.getInstance(EmployeeFundSubService.class);
      String filePath = request.getRealPath("/") + "PayBillPrint";
      String filePathwithName = filePath + "/" + fileName;
      // create the upload folder if not exists
      File folder = new File(filePath);
      if (!folder.exists()) {
        folder.mkdir();
      } else {
        File ex_file = new File(filePath + "/" + fileName);
        if (ex_file.exists()) {
          ex_file.delete();
        }
      }
      map =
          employeeFundSubService.EmployeeFundsUpEPFformDBFPrintOut(
              null,
              request,
              response,
              fileName,
              fileName,
              year,
              month,
              filePathwithName,
              empcategory);
      map.put("fileName", fileName);
      map.put("filePath", filePathwithName);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return map;
  }
コード例 #11
0
 /** 初始化图标。 */
 private List<String> initImages(String path, HttpServletRequest request) {
   List<String> images = new ArrayList<String>();
   File root = new File(request.getRealPath("/") + path);
   File[] files = root.listFiles();
   for (int i = 0; i < files.length; i++) {
     images.add(path + "/" + files[i].getName());
   }
   return images;
 }
コード例 #12
0
 /**
  * @Title: if the file of path then return true else return false @Description: 文件是否存在
  *
  * @param @param path
  * @param @return 设定文件
  * @return boolean 返回类型
  * @throws
  */
 public static boolean fileIsExists(HttpServletRequest request, String path) {
   boolean result = true;
   path = request.getRealPath("") + path;
   File myFile = new File(path);
   if (!myFile.exists()) {
     result = false;
   }
   return result;
 }
コード例 #13
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    System.out.println("开始!" + fileName);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxPostSize);

    try {
      String rootPath = request.getRealPath("/");
      String filePath = rootPath + uploadPath;

      // 若该路径目录不存在,则创建
      File f = new File(filePath);
      if (!f.exists()) {
        f.mkdirs();
      }

      File f2 = new File(filePath + File.separator + fileName + ".jpg");
      if (f2.exists()) {
        out.print("文件已存在");
      } else {
        InputStream inputStream = request.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(f2);

        try {
          int formlength = request.getContentLength();
          byte[] formcontent = new byte[formlength];
          int totalread = 0;
          int nowread = 0;
          while (totalread < formlength) {
            nowread = inputStream.read(formcontent, totalread, formlength);
            totalread += nowread;
          }

          outputStream.write(formcontent);
          outputStream.flush();
        } catch (IOException e) {
          e.printStackTrace();
          out.print("错误:" + e.getMessage());
        } finally {
          outputStream.close();
          inputStream.close();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      out.print("错误:" + e.getMessage());
    } finally {
      out.close();
    }
    System.out.println("结束");
  }
コード例 #14
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    /*
     * // Create path components to save the file final String path =
     * request.getParameter("destination"); final Part filePart =
     * request.getPart("file"); final String fileName =
     * getFileName(filePart);
     */

    String path = request.getContextPath();
    String csvFileToRead = request.getRealPath("/") + "mail.csv";
    BufferedReader br = null;
    String line = "";
    String splitBy = ",";

    JSONArray jArrayMails = new JSONArray();
    try {
      br = new BufferedReader(new FileReader(csvFileToRead));
      while ((line = br.readLine()) != null) {
        jArrayMails.add(line);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();
    jobj.put("studentEmailsArray", jArrayMails);
    out.print(jobj);
  }
コード例 #15
0
ファイル: SoftContoller.java プロジェクト: lancexin/infogiga
 @RequestMapping(value = "/soft", params = "delete")
 public String deleteSoft(
     HttpServletRequest request,
     HttpServletResponse response,
     HttpSession session,
     ModelMap model,
     @RequestParam("softId") Integer softId) {
   Soft soft = manageService.getManageDAO().findById(Soft.class, softId);
   Set attachmentList = soft.getAttachments();
   // System.out.println(attachmentList.size());
   Iterator ite = attachmentList.iterator();
   while (ite.hasNext()) {
     Attachment a = (Attachment) ite.next();
     manageService.getManageDAO().delete(a);
     FileUtil.delete(new File(request.getRealPath(a.getUrl())));
   }
   FileUtil.delete(new File(request.getRealPath(soft.getIcon())));
   FileUtil.delete(new File(request.getRealPath(soft.getPic1())));
   FileUtil.delete(new File(request.getRealPath(soft.getPic2())));
   FileUtil.delete(new File(request.getRealPath(soft.getPic3())));
   FileUtil.delete(new File(request.getRealPath(soft.getPic4())));
   FileUtil.delete(new File(request.getRealPath(soft.getPic5())));
   Set siset = soft.getSoftindexes();
   manageService.getManageDAO().deleteAll(siset);
   try {
     manageService.getManageDAO().delete(soft);
     // msoftService.deleteAttachments(soft, request);
     model.put("success", true);
     model.put("msg", "删除成功!");
     manageService.log(
         Logtype.SOFT,
         ((Users) session.getAttribute("user")).getNickName(),
         "删除软件信息,软件名称为:" + soft.getSoftName());
   } catch (RuntimeException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     model.put("success", false);
     model.put("msg", "删除失败,该软件可能已经投入使用~");
   }
   return "list";
 }
コード例 #16
0
 /**
  * Method execute
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   // TODO Auto-generated method stub
   String storepath = request.getRealPath("/images");
   FacultyMasterDao dao = new FacultyMasterDao();
   CoreList cl = dao.ViewFacultyMaster(storepath);
   request.setAttribute("cl", cl);
   return mapping.findForward("viewFaculty");
 }
コード例 #17
0
ファイル: SoftContoller.java プロジェクト: lancexin/infogiga
 public String saveJPG(HttpServletRequest request, ModelMap model, String url) {
   File of = new File(request.getRealPath(url));
   String suffix = ImageUtil.validateJPG(of);
   if (suffix == null) {
     model.put("success", false);
     model.put("msg", "未能找到文件");
     return null;
   }
   String code = Code.getCode();
   String picUrl =
       ProperiesReader.getInstence("config.properties").getStringValue("material.image.url")
           + code
           + "."
           + suffix;
   boolean bl = FileUtil.copyFile(of, new File(request.getRealPath(picUrl)), false);
   if (bl) {
     return picUrl;
   }
   model.put("success", false);
   model.put("msg", "复制文件出错");
   return null;
 }
コード例 #18
0
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    // InputStream is =  request.getInputStream();

    // InputStreamReader isr = new InputStreamReader(is);
    // char[] c = new char[100];
    // while(isr.read(c)!=-1){
    //	System.out.println(c);
    // }

    String path = request.getRealPath("/");
    String savePath = path + "file\\";
    String tempPath = path + "temp\\";
    File f = new File(tempPath);
    // byte[] b = new byte[1];
    // int len = 0;
    // while((len=is.read(b))!=-1){
    //	fos.write(b,0,len);
    // }
    // fos.flush();
    // fos.close();
    // is.close();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(f);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1024 * 1024 * 1024);
    List<FileItem> items = new ArrayList<FileItem>();
    try {
      items = upload.parseRequest(request);
    } catch (FileUploadException e) {
      e.printStackTrace();
    }
    for (FileItem fileItem : items) {
      System.out.println(fileItem.getName());
      System.out.println(fileItem.getFieldName());
      System.out.println(fileItem.getSize());
      InputStream is = fileItem.getInputStream();
      FileOutputStream fos = new FileOutputStream(savePath + fileItem.getName());
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) != -1) {
        fos.write(b, 0, len);
      }
      fos.flush();
      fos.close();
      is.close();
    }
  }
コード例 #19
0
ファイル: AttachedInfoAction.java プロジェクト: a4m/newsisAP
  public void fileResponse_fortemplate(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    try {

      String path = (String) request.getAttribute("filePath"); // 下载的文件路径
      if (path == null) path = request.getParameter("filePath");

      // 需要限制下载的路径
      String strAllowPath = request.getRealPath("/WEB-INF/template");
      if (path.indexOf("/../") >= 0) {
        //				System.out.println("-------access no auth file:"+path);
        response.getWriter().println("You haven't right to access file:" + path);
        response.flushBuffer();
        return;
      }

      //			System.out.println("--------path="+path);

      java.io.File downloadFile = new java.io.File(strAllowPath + "/" + path);
      java.io.FileInputStream SourceFile = new java.io.FileInputStream(downloadFile);
      OutputStream outputStream = response.getOutputStream();
      try {
        response.setHeader(
            "Content-disposition",
            "attachment; filename=" + java.net.URLEncoder.encode(path, "utf-8"));

        byte readFromFile[] = new byte[1024 * 5];
        int len;
        while ((len = SourceFile.read(readFromFile)) > 0) {
          outputStream.write(readFromFile, 0, len);
        }

      } catch (IOException ie) {
        ie.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        outputStream.flush();
        outputStream.close();
        SourceFile.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #20
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String path = "";
   Vector<ProgrammeTO> studycenters = null;
   Vector<ProgrammeTO> programmeTOs = null;
   String data = request.getParameter("programmeid");
   String[] split = data.split(",");
   String[] names = new String[2];
   for (int i = 0; i < split.length; i++) {
     System.out.println(split[i]);
     names[i] = split[i];
   }
   try {
     programmeTOs = new ProgrammeDelegate().viewProgrammes(request.getRealPath("./images"));
     studycenters =
         new ProgrammeDelegate()
             .viewStudyCenter(request.getRealPath("./images"), Integer.parseInt(names[0]));
     if (!studycenters.isEmpty()) {
       request.setAttribute("status", UtilConstants._VIEW_ADMISSION);
       request.setAttribute("programmeid", names[0]);
       request.setAttribute("programmename", names[1]);
       request.setAttribute("programmeTOs", programmeTOs);
       request.setAttribute("studyCenters", studycenters);
       path = UtilConstants._ADMISSION_FORM;
     } else {
       request.setAttribute("status", UtilConstants._VIEW_STUDY_CENTER_PROGRAMME_FAIL);
       path = UtilConstants._ADMISSION_FORM;
     }
   } catch (Exception e) {
     System.out.println(e);
     request.setAttribute("status", UtilConstants._VIEW_STUDY_CENTER_PROGRAMME_FAIL);
     path = UtilConstants._ADMISSION_FORM;
   }
   RequestDispatcher rd = request.getRequestDispatcher(path);
   rd.forward(request, response);
 }
コード例 #21
0
ファイル: UploadAction.java プロジェクト: araiza233/mavenized
 @Override
 public String execute() {
   try {
     String filePath = request.getRealPath("/") + "\\images\\imagesProducts\\";
     System.out.println("Server path:" + filePath);
     File fileToCreate = new File(filePath, codigo + ".jpg");
     FileUtils.copyFile(file, fileToCreate);
     filePath = fileToCreate.getAbsolutePath();
     ImageCompressor.compress(filePath, filePath.replaceAll(".jpg", "-2.jpg"));
   } catch (Exception e) {
     request.getSession().setAttribute("error", e.getMessage());
     e.printStackTrace();
     return "error";
   }
   return SUCCESS;
 }
コード例 #22
0
 /** <b>这个不能用,他用的是apache的FileUpload</b> 功能描述:使用fileupload components 上传多个文件 */
 public List<Map> UploadFilesByFileupload(HttpServletRequest request) {
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   List<Map> resultList = new ArrayList<Map>();
   if (!isMultipart) {
     return resultList;
   }
   String userfilepath = request.getRealPath("upload");
   DiskFileItemFactory factory = new DiskFileItemFactory();
   factory.setSizeThreshold(2 * 1024 * 1024); // 2MB
   factory.setRepository(new File(userfilepath));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setSizeMax(50 * 1024 * 1024); // 50MB
   try {
     List<FileItem> items = upload.parseRequest(request);
     for (FileItem item : items) {
       if (item.isFormField()) {
         // 普通表单
       } else {
         String fieldName = item.getFieldName();
         String fileName = item.getName();
         // 如果文件域没有填写内容,或者填写的文件不存在
         if ("".equals(fileName) || item.getSize() == 0) {
           continue;
         }
         String date = "/" + fnu.getDate8() + "/";
         String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
         String newfilename = fnu.getUUID() + "." + extName;
         File uploadedFile = new File(userfilepath + date + newfilename);
         if (!uploadedFile.exists()) { // 如果要写入的文件或目录不存在,那么试着创建要写入的目录,以便写入文件
           uploadedFile.getParentFile().mkdirs();
         }
         item.write(uploadedFile);
         Map tmpfile = new HashMap<String, String>();
         tmpfile.put("fieldname", fieldName);
         tmpfile.put(
             "filename",
             fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()));
         tmpfile.put("extname", extName);
         tmpfile.put("filepath", "/upload" + date + newfilename);
         resultList.add(tmpfile);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return resultList;
 }
コード例 #23
0
ファイル: JMServer.java プロジェクト: is00hcw/Mycat-Web
  @SuppressWarnings("deprecation")
  @ResponseBody
  private JSONObject doLocalDump(HttpServletRequest req, String app, String date)
      throws IOException {
    File root = new File(req.getRealPath(req.getRequestURI()));
    String dir = root.getParentFile().getParent();
    File file = new File(String.format("%s/dump/%s_%s_heap.hprof", dir, app, date));
    file.getParentFile().mkdirs();
    String dumpFile = file.getAbsolutePath();
    JMConnManager.getHotspotBean(app).dumpHeap(dumpFile, false);

    JSONObject res = new JSONObject();
    res.put("local", true);
    res.put("file", String.format("./dump/%s", file.getName()));

    return res;
  }
コード例 #24
0
ファイル: TmIpUtil.java プロジェクト: xinshidong/moonVip
 /**
  * 获取省份和城市,传递水晶IP地址库的路径 com.tz.util.ip 方法名:ipLocation 创建人:xuchengfei 手机号码:15074816437
  * 时间:2015年9月15日-下午11:22:05
  *
  * @param request
  * @return 返回类型:String
  * @exception
  * @since 1.0.0
  */
 public static String ipLocation(HttpServletRequest request) {
   if (request == null) return "";
   try {
     String ipLocation = "";
     String ip = getIpAddress(request);
     String path = request.getRealPath("/") + "/ip";
     if (TmStringUtils.isNotEmpty(path)) {
       path = TmStringUtils.conversionSpecialCharacters(path);
       TmIPSeeker ipSeeker = new TmIPSeeker("qqwry.dat", path);
       ipLocation =
           ipSeeker.getIPLocation(ip).getCountry() + " " + ipSeeker.getIPLocation(ip).getArea();
     }
     return ipLocation;
   } catch (Exception e) {
     return "";
   }
 }
コード例 #25
0
 /**
  * 导出入口
  *
  * @param exportType 导出文件的类型
  * @param jaspername jasper文件的名字 如: xx.jasper
  * @param lists 导出的数据
  * @param request
  * @param response
  * @param defaultFilename默认的导出文件的名称
  */
 public static void exportmain(
     String exportType, String jaspername, List lists, String defaultFilename) {
   logger.debug("进入导出    The method======= exportmain() start.......................");
   ActionContext ct = ActionContext.getContext();
   HttpServletRequest request = (HttpServletRequest) ct.get(ServletActionContext.HTTP_REQUEST);
   HttpServletResponse response = ServletActionContext.getResponse();
   String filenurl =
       request.getRealPath("/report/" + jaspername); // jasper文件放在WebRoot/ireport/xx.jasper</span>
   File file = new File(filenurl);
   InputStream is = null;
   try {
     is = new FileInputStream(file);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   export(lists, exportType, defaultFilename, is, request, response);
 }
コード例 #26
0
  /**
   * 生成Excel文件
   *
   * @param request
   * @param response
   * @param workbook
   * @param title
   * @throws Exception
   */
  private File createExportExcel(
      HttpServletRequest request, HttpServletResponse response, XSSFWorkbook workbook, String title)
      throws Exception {
    String servletPath = request.getRealPath("") + "\\upload\\exp";
    String uuid = StringUtil.nextId(); // 生成一个随机UUID。
    java.util.Date currTime = new java.util.Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    String strFolder = formatter.format(currTime);
    String newFileName = servletPath + "\\" + strFolder + "\\" + uuid + ".xls"; // 构成新文件名。

    FileUtil.createDirectorys(servletPath + "\\" + strFolder); // 判断目录是否存在,每天导出的文件都放到对应的一个目录下
    File exportFile = new File(newFileName);

    FileOutputStream os = new FileOutputStream(exportFile); //  文件输出流 
    workbook.write(os); //  将文档对象写入文件输出流
    os.close(); //  关闭文件输出流 
    System.out.println("创建成功 office 2007 excel");
    return exportFile;
  }
コード例 #27
0
 @SkipValidation
 public String deleteTool() {
   try {
     int tid = toolBean.getTID();
     String fileName = toolService.getFileName(tid);
     String filePath = req.getRealPath("/");
     String fullFileName = filePath + "Uploads\\" + fileName;
     logger.debug("Deleting file : " + fullFileName);
     File theFile = new File(fullFileName);
     logger.debug("isFile : " + theFile.isFile());
     logger.debug("File removed = " + theFile.delete());
     toolService.deleteTool(tid);
     addActionMessage("Deletion Successful");
     return getAllTools();
   } catch (Exception e) {
     addActionError("There was a problem while retrieving tool information.Please Contact Admin");
     logger.error(e.getMessage(), e);
     return ERROR;
   }
 }
コード例 #28
0
ファイル: SoftContoller.java プロジェクト: lancexin/infogiga
  private File saveFile(
      HttpServletRequest request, MultipartFile imgFile, String suffix, String code, String path) {
    File file = null;
    try {

      file = new File(request.getRealPath(path) + "\\" + code + suffix);
      if (file.exists()) {
        file.delete();
      }
      imgFile.transferTo(file);
      return file;
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
コード例 #29
0
 /**
  * 用jasperReport导出Pdf
  *
  * @param request
  * @param response
  * @param reportFilePath jasper报表文件路径
  * @param paramMap 字段
  * @param dataList
  * @throws IOException
  * @throws JRException void
  * @author xiaobao @Create Mar 5, 2012 10:01:39 AM
  */
 public static String exportReportToPDF(
     HttpServletRequest request,
     HttpServletResponse response,
     String reportFilePath,
     Map<String, Object> paramMap,
     List dataList)
     throws IOException, JRException {
   JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList);
   String fileName = paramMap.get("fileName").toString();
   fileName = fileName + ".pdf";
   String path =
       request.getRealPath("/")
           + File.separator
           + "report"
           + File.separator
           + "export"
           + File.separator
           + fileName;
   JasperRunManager.runReportToPdfFile(reportFilePath, path, paramMap, dataSource);
   return fileName;
 }
コード例 #30
0
  // *****************************************************
  // Process the initial request from Proshop_main
  // *****************************************************
  //
  @SuppressWarnings("deprecation")
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    //
    //  Prevent caching so sessions are not mangled
    //
    resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1
    resp.setDateHeader("Expires", 0); // prevents caching at the proxy server

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    HttpSession session = SystemUtils.verifyPro(req, out); // check for intruder

    if (session == null) {

      return;
    }

    String club = (String) session.getAttribute("club"); // get club name
    String templott = (String) session.getAttribute("lottery"); // get lottery support indicator
    int lottery = Integer.parseInt(templott);

    //
    //  Call is to display the new features page.
    //
    //  Display a page to provide a link to the new feature page
    //
    out.println("<html><head>");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");
    out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">");
    out.println("<title> \"ForeTees Proshop Announcement Page\"</title>");
    //   out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/web utilities/foretees.css\"
    // type=\"text/css\"></link>");
    out.println(
        "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>");
    out.println("</head>");
    out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\">");

    SystemUtils.getProshopSubMenu(req, out, lottery);

    File f;
    FileReader fr;
    BufferedReader br;
    String tmp = "";
    String path = "";

    try {
      path = req.getRealPath("");
      tmp = "/proshop_features.htm"; // "/" +rev+
      f = new File(path + tmp);
      fr = new FileReader(f);
      br = new BufferedReader(fr);
      if (!f.isFile()) {
        // do nothing
      }
    } catch (FileNotFoundException e) {
      out.println("<br><br><p align=center>Missing New Features Page.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    } catch (SecurityException se) {
      out.println("<br><br><p align=center>Access Denied.</p>");
      out.println("</BODY></HTML>");
      out.close();
      return;
    }

    while ((tmp = br.readLine()) != null) out.println(tmp);

    br.close();

    out.println("</BODY></HTML>");
    out.close();
  } // end of doGet