protected void storeImage(MasterImageMetaData mimd, MultipartFile mpFile) {
    try {
      InputStream imageStream = mpFile.getInputStream();
      log.debug("storeImage: uploaded a multipart file -- filename: " + FILE_UPLOAD_FIELD);

      ImageData imageData = imageResizeMgr.generateImage(imageStream, null, null);
      log.debug("storeImage: file name is: " + mpFile.getOriginalFilename());
      imageData.setFilename(mpFile.getOriginalFilename());

      // Store the image in the cache
      String imageKey = imageCacheManager.addImage(imageData);

      // Uploading a new image
      if (imageKey != mimd.getImageKey()) {
        // Then clear out the previous sized images and their data
        mimd.clearSizedImages();
      }

      // Add the image key and data to the Master Image
      mimd.setImageKey(imageKey);
      mimd.setMetaData(imageData);
    } catch (Exception e) {
      log.debug(
          "storeImage: An exception was caught in storeImage: No inputStream found because no file was uploaded.",
          e.fillInStackTrace());
    }
  }
  // 编辑器上传图片
  @RequestMapping("/upload")
  @ResponseBody
  public JSONObject upload(
      @RequestParam("imgFile") MultipartFile file, HttpServletRequest request, ModelMap m)
      throws IOException {

    // String filetype =
    // StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());

    String realRootPath =
        getServletContext().getResource("/").toString() + "upload/choicenesscontent/" + ymd + "/";
    YztUtil.writeFile(file.getInputStream(), realRootPath, file.getOriginalFilename());

    /**/
    String path = request.getContextPath();
    String basePath =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + path
            + "/";
    // System.out.println("getContextPath==="+
    // basePath+"upload/user/headimg/"+user.getId()+"."+filetype);
    String picurl = basePath + "upload/choicenesscontent/" + ymd + "/" + file.getOriginalFilename();
    // user.setPicurl(picurl);

    JSONObject json = new JSONObject();
    json.put("error", 0);
    json.put("url", picurl);
    return json;
  }
Ejemplo n.º 3
0
 @RequestMapping(value = "/my/upload", method = RequestMethod.POST)
 public @ResponseBody Map upload(
     @RequestParam(value = "upfile", required = true) MultipartFile filedata,
     HttpSession session,
     Model model) {
   ContextUtil.setCurrUser((User) session.getAttribute("user"));
   Map<String, String> rtn = Maps.newHashMap();
   try {
     String path =
         ImageUtils.uploadImages(
             filedata.getOriginalFilename(), filedata.getContentType(), filedata.getBytes());
     Media media = new Media();
     media.setAddress(path);
     media.setStatus(1);
     media.setUploadDate(new Date());
     media.setType(1);
     media.setUserId(ContextUtil.getCurrUser().getId());
     media.setName(filedata.getOriginalFilename());
     media.setLength(filedata.getBytes().length);
     mediaService.addMedia(media);
     rtn.put("state", "FAILED");
     if (path != null) {
       rtn.put("state", "SUCCESS");
       rtn.put("name", filedata.getName());
       rtn.put("originalName", filedata.getOriginalFilename());
       rtn.put("size", String.valueOf(filedata.getSize()));
       rtn.put("type", filedata.getContentType());
       rtn.put("url", ImageUtils.IMAGE_DOMAIN_WITH_PROTOCOL + path);
     }
   } catch (IOException e) {
     rtn.put("state", e.getLocalizedMessage());
   }
   return rtn;
 }
Ejemplo n.º 4
0
  @RequestMapping(method = RequestMethod.POST, value = "/start")
  public ModelAndView start(
      Leave leave,
      ModelAndView mav,
      @RequestParam(value = "leavefile", required = false) MultipartFile leavefile)
      throws Exception {

    String fileUuid = FileUtils.uuidFileName(leavefile.getOriginalFilename());

    // 上传文件
    File targetFile = new File(ServletUtils.getRealPath(request) + "/upload/" + fileUuid);
    leavefile.transferTo(targetFile);

    leave.setFileName(leavefile.getOriginalFilename());
    leave.setFileId(fileUuid);

    current_user = (User) session.getAttribute(Constants.CURRENT_USER);
    leave.setSponsorLoginId(current_user.getLoginId());
    Map<String, Object> variables = new HashMap<String, Object>();
    // 设置流程发起人
    variables.put(WorkflowConstants.SPONSOR, current_user.getName());
    leaveService.startWorkflow(leave, variables);

    mav.setViewName("redirect:/workflow/process");
    return mav;
  }
Ejemplo n.º 5
0
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody String handleFileUpload(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    System.out.println(name + " " + file.getOriginalFilename());
    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream =
            new BufferedOutputStream(
                new FileOutputStream(
                    new File(
                        path
                            + name
                            + "."
                            + FilenameUtils.getExtension(file.getOriginalFilename()))));

        stream.write(bytes);
        stream.close();
        return "You successfully uploaded " + name + "!";
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    } else {
      return "You failed to upload " + name + " because the file was empty.";
    }
  }
  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  @ResponseStatus(value = HttpStatus.OK)
  public Collection<Route> handleFileUpload(@RequestParam("file") MultipartFile file) {
    Collection<Route> result = Collections.emptyList();
    if (!file.isEmpty()) {
      log.info("{} uploaded", file.getOriginalFilename());
      try {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        byte[] data = null;
        if ("zip".equals(extension)) {
          data = zipUtils.doUnzip(file.getBytes());
        } else if ("js".equals(extension)) {
          data = file.getBytes();
        }

        if (data == null) {
          throw new IllegalArgumentException("Unrecognized file extension");
        }

        List<Route> routes = routeCacheFileUtils.parseRoutes(data);
        log.info("Found {} routes", routes.size());
        result = routes;
      } catch (Exception e) {
        log.error("Unexpected error occured while uploading a file", e);
      }
    }
    return result;
  }
Ejemplo n.º 7
0
  // https://github.com/javaswift/joss/blob/master/src/main/java/org/javaswift/joss/model/StoredObject.java
  @Override
  public void storeFile(MultipartFile myFile, String fileId, int fileTTL) throws IOException {
    if (swiftUsername == null) {
      System.out.println("Swift username is not configured");
    }
    assert swiftUsername != null;
    if (config == null) {
      login();
    }
    StoredObject swiftObject = container.getObject(fileId);
    swiftObject.uploadObject(myFile.getInputStream());
    if (myFile.getContentType() != null) {
      swiftObject.setContentType(myFile.getContentType());
    }

    Map<String, Object> metadata = new HashMap<String, Object>();
    if (myFile.getOriginalFilename() != null) {
      metadata.put("filename", myFile.getOriginalFilename());
    }
    if (myFile.getContentType() != null) {
      metadata.put("content-type", myFile.getContentType());
    }
    swiftObject.setMetadata(metadata);
    swiftObject.saveMetadata();
    // swiftObject.setDeleteAt(Date date);
  }
Ejemplo n.º 8
0
  @RequestMapping("/image")
  @ResponseBody
  public ModelMap fileUpload(
      @RequestParam(value = "file") MultipartFile file,
      @RequestParam(value = "name") String name,
      ModelMap model,
      HttpServletRequest request) {

    if (file != null) {
      try {
        // 上传地址
        String path = request.getSession().getServletContext().getRealPath("/upload/headimg/");
        String fileName = file.getOriginalFilename();
        file.transferTo(new File(path, fileName));
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      return null;
    }

    model.put("fileName", file.getOriginalFilename());
    model.put("name", name);
    model.put("date", new Date());
    return model;
  }
  @RequestMapping(value = "/100", method = RequestMethod.POST)
  public @ResponseBody String handleFileUpload(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    log.info("fileName: " + file.getOriginalFilename() + "; fileSize:" + file.getSize());

    if (name == null || name.trim().length() == 0) {
      name = file.getOriginalFilename();
    }

    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream =
            new BufferedOutputStream(new FileOutputStream(new File(name)));
        stream.write(bytes);
        stream.close();
        return "You successfully uploaded (" + file.getOriginalFilename() + ")!";
      } catch (Exception e) {
        return "You failed to upload (" + file.getOriginalFilename() + ") => " + e.getMessage();
      }
    } else {
      return "You failed to upload ("
          + file.getOriginalFilename()
          + ") because the file was empty.";
    }
  }
Ejemplo n.º 10
0
  @RequestMapping(value = "upload", method = RequestMethod.POST)
  public void upload(@RequestParam String memberId, MultipartHttpServletRequest request)
      throws Exception {

    System.out.println("Member Upload...");

    String genId = null;
    String extName = null;
    int fileIndex = 0;
    String filePath = "C:/workspace/Trace/WebContent/traceupload/";

    MultipartFile mpf = null;

    Iterator<String> itr = request.getFileNames();

    while (itr.hasNext()) {
      mpf = request.getFile(itr.next());

      genId = UUID.randomUUID().toString();
      fileIndex = mpf.getOriginalFilename().lastIndexOf(".");
      extName = mpf.getOriginalFilename().substring(fileIndex, mpf.getOriginalFilename().length());

      Member member = new Member();
      member.setMemberId(memberId);
      member.setStoImgName(genId + extName);

      updateMember(member);

      try {
        FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(filePath + genId + extName));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @RequestMapping(value = "/saveProd")
  public String saveProd(
      @Valid Produit p, BindingResult bindingResult, Model model, MultipartFile file)
      throws IOException {
    if (bindingResult.hasErrors()) {
      model.addAttribute("produits", metier.listProduits());
      model.addAttribute("categories", metier.listCategories());
      return ("produits");
    }

    String path = System.getProperty("java.io.tmpdir");

    if (!file.isEmpty()) {
      p.setPhoto(file.getOriginalFilename());
      Long idProd = p.getIdProduit();
      if (p.getIdProduit() == null)
        idProd = metier.ajouterProduit(p, p.getCategorie().getIdCategorie());
      else metier.modifierProduit(p);
      file.transferTo(new File(path + "/PROD_" + idProd + "_" + file.getOriginalFilename()));
    } else {
      if (p.getIdProduit() == null) metier.ajouterProduit(p, p.getCategorie().getIdCategorie());
      else metier.modifierProduit(p);
    }

    model.addAttribute("produit", new Produit());
    model.addAttribute("produits", metier.listProduits());
    model.addAttribute("categories", metier.listCategories());
    return "produits";
  }
Ejemplo n.º 12
0
  @Transactional
  public String upLoadImage(int id, ServletContext servletContext, MultipartFile file) {
    BufferedImage src = null;
    int counter = 0;
    String path = "/resources/chatimgs/";

    path = servletContext.getRealPath(path);
    File destination = null;
    try {
      src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
      if (!(new File(path)).exists()) {
        (new File(path)).mkdir();
      }

      destination = new File(path + String.valueOf(id) + "_" + file.getOriginalFilename());
      while (destination.exists()) {
        counter++;
        destination =
            new File(path + String.valueOf(id) + "_" + counter + "_" + file.getOriginalFilename());
      }
      ImageIO.write(src, "png", destination);
      String finalP = destination.getAbsolutePath().replace('\\', '/');
      int cut = finalP.indexOf("webapp");
      finalP = finalP.substring(cut + 7);
      return finalP;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * 엑셀파일을 업로드하여 우편번호를 등록한다.
   *
   * @param loginVO
   * @param request
   * @param commandMap
   * @param model
   * @return "egovframework/com/sym/ccm/zip/EgovCcmExcelZipRegist"
   * @throws Exception
   */
  @RequestMapping(value = "/sym/ccm/zip/EgovCcmExcelZipRegist.do")
  public String insertExcelZip(
      @ModelAttribute("loginVO") LoginVO loginVO,
      final HttpServletRequest request,
      @RequestParam Map<String, Object> commandMap,
      ZipVO searchVO,
      Model model)
      throws Exception {
    model.addAttribute("searchList", searchVO.getSearchList());

    String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd");
    if (sCmd.equals("")) {
      return "egovframework/com/sym/ccm/zip/EgovCcmExcelZipRegist";
    }

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = multiRequest.getFileMap();
    InputStream fis = null;

    // String sResult = "";

    Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
    MultipartFile file;

    while (itr.hasNext()) {
      Entry<String, MultipartFile> entry = itr.next();

      file = entry.getValue();
      if (!"".equals(file.getOriginalFilename())) {
        // 업로드 파일에 대한 확장자를 체크
        if (file.getOriginalFilename().endsWith(".xls")
            || file.getOriginalFilename().endsWith(".xlsx")
            || file.getOriginalFilename().endsWith(".XLS")
            || file.getOriginalFilename().endsWith(".XLSX")) {

          // zipManageService.deleteAllZip();
          // excelZipService.uploadExcel("ZipManageDAO.insertExcelZip", file.getInputStream(), 2);
          try {
            fis = file.getInputStream();
            if (searchVO.getSearchList().equals("1")) {
              zipManageService.insertExcelZip(fis);
            } else {
              rdnmadZipService.insertExcelZip(fis);
            }
          } finally {
            EgovResourceCloseHelper.close(fis);
          }

        } else {
          LOGGER.info("xls, xlsx 파일 타입만 등록이 가능합니다.");
          return "egovframework/com/sym/ccm/zip/EgovCcmExcelZipRegist";
        }
        // *********** 끝 ***********

      }
    }

    return "forward:/sym/ccm/zip/EgovCcmZipList.do";
  }
Ejemplo n.º 14
0
  @Override
  public ModelMap handleMultipart(
      Do tempDo, ModelMap modelMap, HttpServletRequest request, MultipartRequest multipartRequest)
      throws Exception {
    String introductionId = request.getParameter("master.id");
    MultipartFile multipartFile = multipartRequest.getFile("picurl");

    XSaveOrUpdate xSaveOrUpdate = new XSaveOrUpdate(tempDo.getName(), request);
    HashMap<String, Object> paramMap = xSaveOrUpdate.getParamMap();
    if (multipartFile.getOriginalFilename() != null
        && !multipartFile.getOriginalFilename().equals("")) {
      String url = "work/" + introductionId + "/" + multipartFile.getOriginalFilename();
      aliOssUploadManager.uploadFile(multipartFile, "tenant", url);
      paramMap.put("pictureUrl", url);
    }
    paramMap.put("master.id", introductionId);
    Object object = baseManager.saveOrUpdate(xSaveOrUpdate);

    // 介绍
    String introductionContent = request.getParameter("productDescription");
    ProductDescription productDescription = new ProductDescription();
    productDescription.setContent(introductionContent);
    Product product = new Product();
    product.setId(((MasterWork) object).getId());
    productDescription.setProduct(product);

    baseManager.saveOrUpdate(ProductDescription.class.getName(), productDescription);

    ((MasterWork) object).setProductDescription(productDescription);

    baseManager.saveOrUpdate(MasterWork.class.getName(), object);

    List<String> tagValueList = new ArrayList<>();

    Enumeration<String> paramEnumeration = request.getParameterNames();

    while (paramEnumeration.hasMoreElements()) {
      String paramKey = paramEnumeration.nextElement();
      if (paramKey.startsWith("tag")) {
        String value = request.getParameter(paramKey);
        tagValueList.add(value);
      }
    }

    if (tagValueList.size() > 0) {
      for (String tagId : tagValueList) {
        ProjectTag projectTag = new ProjectTag();
        projectTag.setId(tagId);
        MasterWorkTag masterWorkTag = new MasterWorkTag();
        masterWorkTag.setProjectTag(projectTag);
        masterWorkTag.setMasterWork((MasterWork) object);
        masterWorkTag.setStatus("1");
        baseManager.saveOrUpdate(MasterWorkTag.class.getName(), masterWorkTag);
      }
    }

    modelMap.put("object", object);
    return modelMap;
  }
Ejemplo n.º 15
0
 private static String generateFileName(MultipartFile multipartFile) {
   if (multipartFile.getOriginalFilename() == null
       || "".equals(multipartFile.getOriginalFilename())) {
     return File.DEFAULT_FILENAME + "." + File.DEFAULT_IMAGE_FORMAT;
   } else {
     return multipartFile.getOriginalFilename();
   }
 }
  @RequestMapping(value = "curso/{idCurso}/estrutura/importar", method = RequestMethod.POST)
  public String uploadEstruturaCurricular(
      @PathVariable("idCurso") Integer idCurso,
      @RequestParam("file") MultipartFile request,
      RedirectAttributes redirectAttributes) {

    List<String> infoCurriculo = new ArrayList<String>();

    if (request == null || request.getSize() <= 0) {
      redirectAttributes.addFlashAttribute("error", "Arquivo obrigatório");
      return "redirect:/curso/" + idCurso + "/visualizar";
    }

    if (!request
        .getOriginalFilename()
        .substring(request.getOriginalFilename().indexOf('.'))
        .equals(".html")) {
      redirectAttributes.addFlashAttribute(
          "error", "Formato inválido de arquivo. Por favor selecione um arquivo HTML");
      return "redirect:/curso/" + idCurso + "/visualizar";
    }

    try {
      if (parserEstruturaCurricular.verificaConformidadeDocumeto(request, idCurso) == false) {
        redirectAttributes.addFlashAttribute(
            "error",
            "O documento enviado não apresenta uma estrutura curricular do Curso de "
                + cursoService.getCursoByCodigo(idCurso).getNome());
        return "redirect:/curso/" + idCurso + "/visualizar";
      }
    } catch (IOException e1) {
      e1.printStackTrace();
      redirectAttributes.addFlashAttribute(
          "error", "Não foi possível o upload das informações. Por favor tente novamente");
      return "redirect:/curso/" + idCurso + "/visualizar";
    }

    try {
      infoCurriculo = parserEstruturaCurricular.processarArquivo(idCurso);
    } catch (Exception e) {
      System.err.println("Erro ao processar arquivo: " + e.getMessage());
      return "redirect:/curso/" + idCurso + "/visualizar";
    }

    Curso curso = cursoService.getCursoByCodigo(idCurso);

    if (estruturaCurricularService.getOutraEstruturaCurricularByCodigoSemestre(
            curso.getId(), infoCurriculo.get(0))
        == null) {
      parserEstruturaCurricular.registrarNovaEstruturaCurricular(infoCurriculo, curso);
      redirectAttributes.addFlashAttribute("info", "Estrutura cadastrada com sucesso");
    } else {
      redirectAttributes.addFlashAttribute("error", "Estrutura já cadastrada");
    }

    return "redirect:/curso/" + idCurso + "/visualizar";
  }
Ejemplo n.º 17
0
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public String upload(@RequestParam MultipartFile uploadFile, @RequestParam String comment)
      throws IOException {
    File file = new File("c:/Temp/upload/" + uploadFile.getOriginalFilename());

    Model model = null;
    model.addAttribute("uploaded", uploadFile.getOriginalFilename());
    uploadFile.transferTo(file);

    return "upload/uploadResult";
  }
Ejemplo n.º 18
0
 /**
  * @param file //文件对象
  * @param filePath //上传路径
  * @param fileName //文件名
  * @return 文件名
  */
 public static String fileUp(MultipartFile file, String filePath, String fileName) {
   String extName = ""; // 扩展名格式:
   try {
     if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
       extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
     }
     copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
   } catch (IOException e) {
     e.printStackTrace();
   }
   return fileName + extName;
 }
Ejemplo n.º 19
0
  @RequestMapping(value = "upload")
  public String upload(
      @RequestParam("fileupload") MultipartFile file,
      String guanming,
      String sum,
      SchoolBag schoolBag,
      HttpServletRequest request,
      HttpServletResponse response,
      Model model)
      throws IOException {

    String imgPath = null;
    System.out.println("模板:" + schoolBag.getMoban());
    System.out.println("冠名:" + guanming);
    System.out.println("总和:" + sum);
    if (schoolBag.getMoban().equals("3")) {
      if (!file.isEmpty()) {
        String image = null;
        try {
          String name =
              file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
          image = UUID.randomUUID().toString() + name;
          imgPath =
              request.getSession().getServletContext().getRealPath("/views/headImg") + "/" + image;
          file.transferTo(new File(imgPath));
        } catch (Exception e) {
          return "error";
        }
        schoolBag.setBgtype("/views/headImg/" + image);
      }
    }
    try {
      Map<Object, Object> map = request.getParameterMap();
      schoolBag.setNumN(Integer.parseInt(sum));
      schoolBag.setHeadImage(guanming);
      schoolBag.setDateN(DateUtils.getDate("yyyy-MM-dd"));
      String bagId = schoolBagService.save(schoolBag, map, Integer.parseInt(sum));
      System.out.println("生成的红包Id:" + bagId);
      model.addAttribute("bagId", bagId);
      model.addAttribute("schoolbagId", schoolBag.getId());
      return "redirect:/schoolBag/schoolBagOK";
    } catch (Exception e) {
      if (imgPath != null) {
        File f = new File(imgPath);
        if (f.exists()) {
          f.delete();
        }
      }
      return "error";
    }
  }
Ejemplo n.º 20
0
  /**
   * 文件上传
   *
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping(value = "/upload")
  public void fileupload(MultipartHttpServletRequest request, HttpServletResponse response)
      throws Exception {
    UserBasicInfo user = UserBasicInfo.getFromSession(request);

    List<MultipartFile> list = request.getFiles("files");

    String rtMsg = ""; // 返回的消息
    String fids = ""; // 成功上传后的ID
    String fnames = ""; // 成功上传的文件
    Iterator<MultipartFile> it = list.iterator();
    while (it.hasNext()) {
      MultipartFile file = it.next();
      if (file.getSize() <= 0 || "".equals(file.getOriginalFilename())) {
        continue;
      }
      String fname = file.getOriginalFilename();
      String vldMsg = FileUploadValidator.validate(file);

      if (vldMsg != null) {
        rtMsg += "\r\n" + fname + ":\t" + vldMsg;
        continue;
      }
      // TODO 文件别名、备注等信息
      String alisName = fname; // 文件别名
      String remark = ""; // 备注
      float fsize = file.getSize() / 1024; // 文件大小
      String fullpath = FileUploadUtil.upload(file, alisName); // 上传并返回路径
      String fileExt = FileUploadUtil.getFileExt(fname); // 文件类型
      long attId =
          attachmentService.insert(alisName, fullpath, fsize, fileExt, remark, user.getUserId());
      fids += attId + ",";
      fnames += fname + ",";
    }

    // 输出
    JSONObject json = new JSONObject();
    if (!"".equals(rtMsg)) {
      json.put("xukea_type", "error");
      json.put("xukea_status", BaseConstants.HTTP_SERVER_ERROR);
      json.put("xukea_msg", "以下文件上传失败" + rtMsg);
    } else {
      json.put("xukea_type", "success");
      json.put("xukea_status", BaseConstants.HTTP_OK);
      json.put("xukea_msg", "所有文件上传成功");
    }
    json.put("data", "{ids:'" + fids + "', fnames:'" + fnames + "'}");
    String cntype = "text/html";
    this.output(request, response, cntype, json.toString());
  }
  /**
   * 설문템플릿를 수정처리 한다.
   *
   * @param multiRequest
   * @param searchVO
   * @param commandMap
   * @param qustnrTmplatManageVO
   * @param bindingResult
   * @param model
   * @return "/uss/olp/qtm/EgovQustnrTmplatManageModifyActor"
   * @throws Exception
   */
  @RequestMapping(value = "/uss/olp/qtm/EgovQustnrTmplatManageModifyActor.do")
  public String QustnrTmplatManageModifyActor(
      final MultipartHttpServletRequest multiRequest,
      @ModelAttribute("searchVO") ComDefaultVO searchVO,
      Map commandMap,
      @ModelAttribute("qustnrTmplatManageVO") QustnrTmplatManageVO qustnrTmplatManageVO,
      BindingResult bindingResult,
      ModelMap model)
      throws Exception {

    // 0. Spring Security 사용자권한 처리
    Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
    if (!isAuthenticated) {
      model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
      return "uat/uia/EgovLoginUsr";
    }

    // 로그인 객체 선언
    LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();

    // 서버  validate 체크
    beanValidator.validate(qustnrTmplatManageVO, bindingResult);
    if (bindingResult.hasErrors()) {
      model.addAttribute(
          "resultList",
          egovQustnrTmplatManageService.selectQustnrTmplatManageDetail(qustnrTmplatManageVO));
      return "/uss/olp/qtm/EgovQustnrTmplatManageModify";
    }

    // 아이디 설정
    qustnrTmplatManageVO.setFrstRegisterId((String) loginVO.getUniqId());
    qustnrTmplatManageVO.setLastUpdusrId((String) loginVO.getUniqId());

    final Map<String, MultipartFile> files = multiRequest.getFileMap();

    if (!files.isEmpty()) {
      for (MultipartFile file : files.values()) {
        System.out.println("getName =>" + file.getName());
        System.out.println("getOriginalFilename =>" + file.getOriginalFilename());
        // log.info("getOriginalFilename =>" + file.getOriginalFilename() );
        if (file.getName().equals("qestnrTmplatImage") && !file.getOriginalFilename().equals("")) {
          qustnrTmplatManageVO.setQestnrTmplatImagepathnm(file.getBytes());
        }
      }
    }
    egovQustnrTmplatManageService.updateQustnrTmplatManage(qustnrTmplatManageVO);

    return "redirect:/uss/olp/qtm/EgovQustnrTmplatManageList.do";
  }
Ejemplo n.º 22
0
 // 上传资源
 @RequestMapping(value = "/uploadSource")
 public String uploadSource(
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam(value = "sourceFile") MultipartFile file,
     Model model) {
   String orName = file.getOriginalFilename();
   String houzui = "";
   if (orName.lastIndexOf(".") != -1) {
     houzui = orName.substring(orName.lastIndexOf("."));
   }
   String imgPath = init.getImgPath();
   File parent = new File(imgPath + "newSource/");
   if (!parent.exists()) {
     parent.mkdirs();
   }
   String filename = UuidUtils.getImgUUID() + houzui;
   File target = new File(parent, filename);
   // 如果大于200K,则进行压缩
   try {
     FileUtils.copyInputStreamToFile(file.getInputStream(), target);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // 回传结果
   ImgUploadResult imgUploadResult = new ImgUploadResult();
   imgUploadResult.setError(0);
   imgUploadResult.setUrl("/imgStore/newSource/" + filename);
   model.addAttribute("json", JSONUtil.object2json(imgUploadResult));
   return JSON;
 }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {

    SysMsgCommand msgCmd = (SysMsgCommand) command;
    log.info("SysMsgDetailController:onSubmit called.");

    NotificationDto sysMessage = msgCmd.getMsg();
    String btn = request.getParameter("btn");
    if ("delete".equalsIgnoreCase(btn)) {
      if (sysMessage.getType() == NotificationType.SYSTEM) {
        return null;
      }
      sysMessageService.removeMessage(sysMessage.getMsgId());
      ModelAndView mav = new ModelAndView("/deleteconfirm");
      mav.addObject("msg", "Location has been successfully deleted.");
      return mav;
    } else {
      if (msgCmd.getTemplateMethod() == 0) {
        MultipartFile providerScriptFile = msgCmd.getProviderScriptFile();
        String providerScriptFileName = "";
        if (providerScriptFile != null && providerScriptFile.getSize() > 0) {
          providerScriptFileName = providerScriptFile.getOriginalFilename();
          String filePath = res.getString("scriptRoot") + "/msgprovider/" + providerScriptFileName;
          File dest = new File(filePath);
          try {
            providerScriptFile.transferTo(dest);
            sysMessage.setProviderScriptName(providerScriptFileName);
            sysMessage.setMailTemplate(null);
          } catch (IllegalStateException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      } else {
        MailTemplateDto mailTemplateDto =
            mailTemplateWebService
                .getTemplateById(msgCmd.getSelectedTemplateId())
                .getMailTemplate();
        sysMessage.setMailTemplate(mailTemplateDto);
        sysMessage.setProviderScriptName(null);
      }

      if (StringUtils.isEmpty(sysMessage.getMsgId())) {
        sysMessageService.addMessage(sysMessage);
      } else {
        sysMessageService.updateMessage(sysMessage);
      }
    }

    ModelAndView mav = new ModelAndView(new RedirectView(redirectView, true));
    mav.addObject("sysMsgCmd", msgCmd);

    return mav;
  }
  /*
   @RequestMapping(value = "/uploadfile.html", method = RequestMethod.GET)
   public String uploadFile(){
   	return "uploadfile";
   }
  */
  @RequestMapping(value = "/uploadfile.html", method = RequestMethod.POST)
  public String processUploadPreview(
      @RequestParam("file") MultipartFile file,
      @RequestParam("id") Integer recordId,
      Map<String, Object> respMap) {
    Record record = recordService.getRecord(recordId);
    respMap.put("record", record);
    if (record == null) {
      // respMap.put("errMesg", "Incorect or not available record");
      return "redirect:records.html";
    }
    respMap.put("id", recordId);
    if (file.getSize() > 5242880) {
      respMap.put("errMesg", "Max file size 5MB");
      return "redirect:editrecord.html";
    }
    if (file.getName().equals("")) {
      respMap.put("errMesg", "File not selected");
      return "redirect:editrecord.html";
    }

    File newFile = new File();
    newFile.setRecord(record);
    newFile.setFilename(file.getOriginalFilename());
    newFile.setType(file.getName());
    try {
      newFile.setFile(file.getBytes());
      fileService.addFilele(newFile);
    } catch (Exception e) {
      respMap.put("errMesg", "Server error");
      e.printStackTrace();
      return "redirect:editrecord.html";
    }
    return "redirect:editrecord.html";
  }
Ejemplo n.º 25
0
  @RequestMapping(value = "addBlogs.action", method = RequestMethod.POST)
  @ResponseBody
  public Object addBlogs(Blogs blogs, HttpServletRequest request) throws IOException {
    User_Ext_Personal user_Ext_Personal = PublicUtil.getUserOfSession(request);
    if (user_Ext_Personal == null) {
      return "needLogin";
    }
    blogs.setUserid(user_Ext_Personal.getUserId());

    MultipartHttpServletRequest httpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = httpServletRequest.getFile("image");
    String fileName = file.getOriginalFilename();
    byte[] b = file.getBytes();
    File dirFile =
        new File(PublicUtil.getRootFileDirectory(request) + "/media_upload/personal_upload");
    if (!dirFile.exists()) {
      dirFile.mkdirs();
    }
    String imagepath =
        "/media_upload/personal_upload/" + new Hanyu().getStringPinYin(blogs.getTitle()) + fileName;
    File files = new File(PublicUtil.getRootFileDirectory(request) + imagepath);
    if (!files.exists()) {
      dirFile.createNewFile();
    }

    FileCopyUtils.copy(b, files);

    boolean bool = blogsService.addBlogs(blogs, imagepath, null);

    return bool + "";
  }
Ejemplo n.º 26
0
  @RequestMapping(value = "add", method = RequestMethod.POST)
  public String add(
      String name,
      String email,
      String tel,
      String cid,
      String password,
      MultipartFile photofile,
      Model model)
      throws Exception {

    String newFileName = null;

    if (photofile.getSize() > 0) {
      newFileName = MultipartHelper.generateFilename(photofile.getOriginalFilename());
      File attachfile = new File(servletContext.getRealPath(SAVED_DIR) + "/" + newFileName);
      photofile.transferTo(attachfile);

      makeThumbnailImage(
          servletContext.getRealPath(SAVED_DIR) + "/" + newFileName,
          servletContext.getRealPath(SAVED_DIR) + "/s-" + newFileName + ".png");
    }

    Student student = new Student();
    student.setName(name);
    student.setEmail(email);
    student.setTel(tel);
    student.setCid(cid);
    student.setPassword(password);
    student.setPhoto(newFileName);

    studentDao.insert(student);

    return "redirect:list.do";
  }
Ejemplo n.º 27
0
 /** 功能:添加修改 */
 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public ModelAndView save(@RequestParam MultipartFile[] images, String gid) throws Exception {
   ModelAndView mav =
       new ModelAndView(com.baofeng.utils.Constants.COREWEB_BUILDITEMS + "/musicbg");
   MusicBg music = new MusicBg();
   if (images != null && images.length > 0) {
     for (MultipartFile $file : images) {
       if (!$file.isEmpty()) {
         String name = $file.getOriginalFilename();
         String ext = name.substring(name.lastIndexOf("."), name.length());
         String sha1 = DigestUtils.shaHex($file.getInputStream());
         String fileName = sha1 + ext;
         String path =
             Constants.DEFAULT_UPLOADIMAGEPATH + File.separator + Constants.sha1ToPath(sha1);
         Constants.mkdirs(path);
         FileUtils.copyInputStreamToFile($file.getInputStream(), new File(path, fileName));
         music.setImageSha1(sha1);
         music.setImage(fileName);
       }
     }
   }
   this.musicBgService.addMusicBg(music, gid);
   WeekService week = this.weekServiceService.readWeekService(gid);
   if (week != null) {
     mav.addObject("week", week);
   }
   return mav;
 }
Ejemplo n.º 28
0
 /** 功能:修改图片 */
 @ResponseBody
 @RequestMapping(value = "/upLoadImages", method = RequestMethod.POST)
 public ResultMsg upLoadImages(String id2, @RequestParam MultipartFile[] images2, String gid)
     throws Exception {
   ResultMsg result = new ResultMsg();
   result.setResultMessage("errors");
   MusicBg music = new MusicBg();
   if (images2 != null && images2.length > 0) {
     for (MultipartFile $file : images2) {
       if (!$file.isEmpty()) {
         String name = $file.getOriginalFilename();
         String ext = name.substring(name.lastIndexOf("."), name.length());
         String sha1 = DigestUtils.shaHex($file.getInputStream());
         String fileName = sha1 + ext;
         String path =
             Constants.DEFAULT_UPLOADIMAGEPATH + File.separator + Constants.sha1ToPath(sha1);
         Constants.mkdirs(path);
         FileUtils.copyInputStreamToFile($file.getInputStream(), new File(path, fileName));
         music.setImageSha1(sha1);
         music.setImage(fileName);
       }
     }
   }
   music.setId(id2);
   if (this.musicBgService.addMusicBg(music, gid)) {
     result.setResultMessage("success");
   }
   return result;
 }
Ejemplo n.º 29
0
  @ResponseBody
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public ImmutableMap<String, String> linkImgUpload(
      MultipartFile file, HttpServletRequest request) {
    if (file.isEmpty()) {
      return ImmutableMap.of("status", "0", "message", getMessage("global.uploadempty.message"));
    }
    Site site = (Site) (SystemUtils.getSessionSite());
    String linkPath = PathFormat.parseSiteId(SystemConstant.LINK_RES_PATH, site.getSiteId() + "");
    String realPath = HttpUtils.getRealPath(request, linkPath);

    SystemUtils.isNotExistCreate(realPath);

    String timeFileName = SystemUtils.timeFileName(file.getOriginalFilename());
    try {
      file.transferTo(new File(realPath + "/" + timeFileName));
    } catch (IOException e) {
      LOGGER.error("链接图片添加失败,错误:{}", e.getMessage());
      return ImmutableMap.of("status", "0", "message", getMessage("link.uploaderror.message"));
    }
    return ImmutableMap.of(
        "status",
        "1",
        "message",
        getMessage("link.uploadsuccess.message"),
        "filePath",
        (linkPath + "/" + timeFileName),
        "contentPath",
        HttpUtils.getBasePath(request));
  }
  @RequestMapping(value = "codiRoomMyClothesUpload", method = RequestMethod.POST)
  public String codiRoomMyClothesUpload(
      Clothes clothes, MultipartFile file, HttpServletRequest request) throws IOException {

    if (!file.isEmpty()) {

      ServletContext application = request.getServletContext();
      String url = "/resource/image/clothes";
      String path = application.getRealPath(url);
      String temp = file.getOriginalFilename();
      String fname = temp.substring(temp.lastIndexOf("\\") + 1);
      String fpath = path + "\\" + fname;

      InputStream ins = file.getInputStream(); // part.getInputStream();
      OutputStream outs = new FileOutputStream(fpath);

      byte[] buffer = new byte[1024];

      int len = 0;

      while ((len = ins.read(buffer, 0, 1024)) >= 0) outs.write(buffer, 0, len);

      outs.flush();
      outs.close();
      ins.close();

      clothes.setImage(fname);
    }

    clothesDao.addClothes(clothes);

    return "redirect:codiRoomMyClothes";
  }