Exemplo n.º 1
1
  /** Upload single file using Spring Controller */
  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  public @ResponseBody String uploadFileHandler(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        System.out.println("Upload path " + dir);
        if (!dir.exists()) dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());

        return "You successfully uploaded file=" + name;
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    } else {
      return "You failed to upload " + name + " because the file was empty.";
    }
  }
Exemplo n.º 2
0
  // Adding new snippet - POST
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String setAddSnippet(
      @ModelAttribute("newSnippet") Snippet newSnippet, HttpServletRequest request) {
    MultipartFile snippetImage = newSnippet.getSnippetImage();
    MultipartFile snippetFile = newSnippet.getSnippetFile();

    String rootDirectory = request.getSession().getServletContext().getRealPath("/");

    // Adding snippet image
    if (snippetImage != null && !snippetImage.isEmpty()) {
      try {
        snippetImage.transferTo(
            new File(rootDirectory + "resources\\images\\" + newSnippet.getSnippetId() + ".png"));
      } catch (Exception e) {
        throw new RuntimeException("Snippet Image saving failed", e);
      }
    }

    // Adding snippet file
    if (snippetFile != null && !snippetFile.isEmpty()) {
      try {
        snippetFile.transferTo(
            new File(rootDirectory + "resources\\files\\" + newSnippet.getSnippetId() + ".pdf"));
      } catch (Exception e) {
        throw new RuntimeException("Snippet File saving failed", e);
      }
    }
    snippetService.addSnippet(newSnippet);
    return "redirect:/snippets/all";
  }
Exemplo n.º 3
0
  // pathname : 파일을 저장할 경로
  // 리턴 : 서버에 저장된 새로운 파일명
  public String doFileUpload(MultipartFile partFile, String pathname) throws Exception {
    String saveFilename = null;

    if (partFile == null || partFile.isEmpty()) return null;

    // 클라이언트가 업로드한 파일의 이름
    String originalFilename = partFile.getOriginalFilename();
    if (originalFilename == null || originalFilename.length() == 0) return null;

    // 확장자
    String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
    if (fileExt == null || fileExt.equals("")) return null;

    // 서버에 저장할 새로운 파일명을 만든다.
    saveFilename = String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", Calendar.getInstance());
    saveFilename += System.nanoTime();
    saveFilename += fileExt;

    String fullpathname = pathname + File.separator + saveFilename;
    // 업로드할 경로가 존재하지 않는 경우 폴더를 생성 한다.
    File f = new File(fullpathname);
    if (!f.getParentFile().exists()) f.getParentFile().mkdirs();

    partFile.transferTo(f);

    return saveFilename;
  }
  @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";
  }
Exemplo n.º 5
0
  /** 上传 */
  @RequestMapping(value = "uploadFile.do")
  @ResponseBody
  public Map<String, Object> uploadFile(HttpServletRequest request, HttpServletResponse response) {
    try {
      // 转型为MultipartHttpRequest
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      // 根据前台的name名称得到上传的文件
      MultipartFile file = multipartRequest.getFile("upfile");
      if (!file.isEmpty()) {
        if (file.getSize()
            > FileUtils.ONE_MB
                * Integer.parseInt(propertyReader.getValue("UploadFileMaxSize"), 10)) {
          jsonMap.put(
              "message",
              propertyReader.getValue("FileSizeExceed")
                  + propertyReader.getValue("UploadFileMaxSize")
                  + "m");
          return jsonMap;
        }
        // 文件名
        String fileName = file.getOriginalFilename();

        // TODO:上传文件
        // file.transferTo();
        jsonMap.put("fileName", fileName);
        jsonMap.put("success", true);
      }
    } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
    }
    return jsonMap;
  }
Exemplo n.º 6
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));
  }
  @Override
  public void addOrUpdatePerson(
      TSysPerson person, MultipartFile photo, String savePath, String urlPath) throws IOException {
    if (photo != null && !photo.isEmpty()) {
      long currentTimeMillis = System.currentTimeMillis();
      String fileType = FilenameUtils.getExtension(photo.getOriginalFilename());
      String thumbnailName = person.getUserId() + "_" + currentTimeMillis + fileType;
      String photoName = person.getUserId() + "_" + currentTimeMillis + "_original" + fileType;

      File dir = new File(savePath);
      if (!dir.exists() || !dir.isDirectory()) {
        dir.delete();
        dir.mkdirs();
      }
      FileUtils.copyInputStreamToFile(photo.getInputStream(), new File(dir, photoName));
      ImageUtils.process(
          savePath + photoName, 256, 256, true, 0, null, null, 0, savePath + thumbnailName);
      person.setPhoto(urlPath + thumbnailName);
    }

    person.setSpell(
        PinyinUtils.getPinyin(person.getNickname())
            + " "
            + PinyinUtils.getPinyinHead(person.getNickname()));
    this.baseDao.saveOrUpdate(person);
  }
Exemplo n.º 8
0
  @RequestMapping(value = "fetchSimilarImage", method = RequestMethod.POST)
  public @ResponseBody List<Map<Object, Object>> fetchSimilarImage(
      @RequestParam("doc") MultipartFile doc, HttpServletRequest request) throws Exception {
    List<Map<Object, Object>> resultlist = new ArrayList<Map<Object, Object>>();
    if (doc.isEmpty()) {
      return resultlist;
    }

    ServletContext sc = request.getSession().getServletContext();
    String uploadpath = sc.getRealPath("/src/upload");
    String indexpath = sc.getRealPath("/src/imgindex");
    String imageName = System.currentTimeMillis() + ".png";
    File savefile = new File(new File(uploadpath), imageName);
    if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
    doc.transferTo(savefile); // save file
    List<Image> list = imageService.findSimilarImage(uploadpath + "/" + imageName, indexpath, 100);
    if (list != null && list.size() > 0) {
      int size = list.size();
      for (int index = size - 1; index >= 0; index--) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("score", list.get(index).getScore());
        map.put("imageurl", list.get(index).getImagepath());
        resultlist.add(map);
      }
    }
    return resultlist;
  }
Exemplo n.º 9
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;
 }
Exemplo n.º 10
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;
 }
Exemplo n.º 11
0
  @RequestMapping(value = "/batchUpload", method = RequestMethod.POST)
  @ResponseBody
  public Map<String, String> upload(int userId, BatchPhotoModel_old model) {

    Map<String, String> result = new HashMap<String, String>();
    List<MultipartFile> files = model.getFiles();
    try {

      File path = new File(PREFIX);
      if (!path.exists()) {
        path.mkdirs();
      }

      for (int i = 0; i < files.size(); i++) {

        MultipartFile file = files.get(i);

        if (!file.isEmpty()) {
          byte[] bytes = file.getBytes();
          fildUpload(generatePathByUserId(userId, i), bytes);
        }
      }
      result.put("state", "success");
      return result;

    } catch (IOException ioe) {
      logger.error("Error uploading photo, userId:" + userId, ioe);
    }
    result.put("state", "failure");
    return result;
  }
Exemplo n.º 12
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.";
    }
  }
Exemplo n.º 13
0
  @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.";
    }
  }
  @RequestMapping(value = "developReport/report", method = RequestMethod.POST)
  public ModelAndView uploadReportFile(
      @RequestParam("file") final MultipartFile file, final HttpServletRequest request) {
    if (!showReportDevelopment) {
      return new ModelAndView(new RedirectView("/"));
    }

    if (file.isEmpty()) {
      return new ModelAndView(L_QCADOO_REPORT_REPORT).addObject("isFileInvalid", true);
    }

    try {
      String template = IOUtils.toString(file.getInputStream());

      List<ReportParameter> params = getReportParameters(template);

      return new ModelAndView(L_QCADOO_REPORT_REPORT)
          .addObject(L_TEMPLATE, template)
          .addObject("isParameter", true)
          .addObject(L_PARAMS, params)
          .addObject(L_LOCALE, "en");
    } catch (Exception e) {
      return showException(L_QCADOO_REPORT_REPORT, e);
    }
  }
  @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";
  }
  /**
   * Uploads the dsl file of a user to an auxiliar folder, if it's not upload returns an error
   *
   * @param file
   * @param idUser
   */
  @RequestMapping(method = RequestMethod.POST, value = "/uploadDSL")
  public ResponseEntity<String> handleFileUploadDSL(
      @RequestParam("dsl") MultipartFile file, @RequestParam("idUser") String idUser) {

    // target DSL name
    String name = "dsl.yml";
    if (!file.isEmpty()) {
      try {
        // User folder
        File userFolder = new File(idUser);
        if (!userFolder.exists()) Files.createDirectory(userFolder.toPath());
        // Auxiliar folder where the temporal configuration files are
        // copy
        String folderAux = idUser + "/aux";
        File folder = new File(folderAux);
        if (!folder.exists()) Files.createDirectory(folder.toPath());
        // Copy DSL file
        BufferedOutputStream stream =
            new BufferedOutputStream(new FileOutputStream(new File(folderAux + "/" + name)));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        log.info("DSL copied: " + idUser);
      } catch (Exception e) {
        log.warn("DSL not copied:" + e.getMessage());
        throw new InternalError("Error copying: " + e.getMessage());
      }
    } else {
      log.warn("DSL not copied, empty file: " + idUser);
      throw new BadRequestError("Empty file");
    }
    return new ResponseEntity<>("copied", HttpStatus.OK);
  }
Exemplo n.º 17
0
  public static void upload(String path, MultipartFile file, String fileName) {
    if (!file.isEmpty()) {
      InputStream inputStream = null;
      OutputStream outputStream = null;
      if (file.getSize() > 0) {
        try {
          inputStream = file.getInputStream();
          outputStream = new FileOutputStream(path + file);
          int readBytes = 0;
          byte[] buffer = new byte[1024];
          while ((readBytes = inputStream.read(buffer, 0, 1024)) != -1) {
            outputStream.write(buffer, 0, readBytes);
          }
        } catch (IOException e) {
          e.printStackTrace();

        } finally {
          try {
            outputStream.close();
            inputStream.close();

          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
Exemplo n.º 18
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) {
     }
   }
 }
  @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;
  }
Exemplo n.º 20
0
 /** {@inheritDoc} */
 public File saveMultipart(MultipartFile file, File dir) throws IOException {
   if (file.isEmpty()) {
     return null;
   }
   File tempFile = File.createTempFile("LPGLIMS", ".jrxml", dir);
   file.transferTo(tempFile);
   return tempFile;
 }
Exemplo n.º 21
0
 private boolean saveImage(
     Product product, ProductExt bean, ProductType type, MultipartFile file, String uploadPath) {
   // 如果没有上传文件,则不处理。
   if (file == null || file.isEmpty()) {
     return false;
   }
   // 先删除图片,如果有的话。
   deleteImage(product, uploadPath);
   // 获得后缀
   String ext = FilenameUtils.getExtension(file.getOriginalFilename());
   // 检查后缀是否允许上传
   if (!ImageUtils.isImage(ext)) {
     return false;
   }
   // 日期目录
   String dateDir = FileNameUtils.genPathName();
   // 创建目录
   File root = new File(uploadPath, dateDir);
   // 相对路径
   String relPath = SPT + dateDir + SPT;
   if (!root.exists()) {
     root.mkdirs();
   }
   // 取文件名
   String name = FileNameUtils.genFileName();
   // 保存为临时文件
   File tempFile = new File(root, name);
   try {
     file.transferTo(tempFile);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   try {
     // 保存详细图
     String detailName = name + Product.DETAIL_SUFFIX + POINT + ext;
     File detailFile = new File(root, detailName);
     imageScale.resizeFix(
         tempFile, detailFile, type.getDetailImgWidth(), type.getDetailImgHeight());
     bean.setDetailImg(relPath + detailName);
     // 保存列表图
     String listName = name + Product.LIST_SUFFIX + POINT + ext;
     File listFile = new File(root, listName);
     imageScale.resizeFix(tempFile, listFile, type.getListImgWidth(), type.getListImgHeight());
     bean.setListImg(relPath + listName);
     // 保存缩略图
     String minName = name + Product.MIN_SUFFIX + POINT + ext;
     File minFile = new File(root, minName);
     imageScale.resizeFix(tempFile, minFile, type.getMinImgWidth(), type.getMinImgHeight());
     bean.setMinImg(relPath + minName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   // 删除临时文件
   tempFile.delete();
   return true;
 }
Exemplo n.º 22
0
  /**
   * 객실을 추가하는 메서드(경준오빠가 완성해야함)
   *
   * @param request
   * @return
   */
  @RequestMapping(value = "room.addRoom.do", produces = "text/plain;charset=UTF-8")
  public ModelAndView addRoom(HttpServletRequest request, RoomPics dto) throws Exception {
    System.out.println("##Debug_in_roomController: addRoom()실행");
    ModelAndView mv = new ModelAndView();
    int roomTypeNo = Integer.parseInt((String) request.getParameter("typeName"));
    String typeName = "";
    if (roomTypeNo == 1) {
      typeName = "SINGLE ROOM";
    } else if (roomTypeNo == 2) {
      typeName = "TWIN ROOM";
    } else if (roomTypeNo == 3) {
      typeName = "DOUBLE ROOM";
    } else if (roomTypeNo == 4) {
      typeName = "DELUX ROOM";
    } else if (roomTypeNo == 5) {
      typeName = "SUITE ROOM";
    } else if (roomTypeNo == 6) {
      typeName = "PRESIDENT ROOM";
    }

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("roomNo", Integer.parseInt((String) request.getParameter("roomNo")));
    map.put("roomTypeNo", Integer.parseInt((String) request.getParameter("typeName")));
    map.put("limitNum", Integer.parseInt((String) request.getParameter("limitNum")));
    map.put("bed", request.getParameter("bed"));
    map.put("floor", request.getParameter("floor"));
    map.put("typeName", typeName);
    map.put("bed", request.getParameter("bed"));
    map.put("price", request.getParameter("price"));

    boolean flag = service.addRoom(map);
    System.out.println("##debug addroom 결과: " + flag);

    MultipartFile multi = dto.getFile();

    if (!multi.isEmpty()) { // 파일업로드가 되었다면
      String orgName = multi.getOriginalFilename();
      String newName = System.currentTimeMillis() + multi.getSize() + orgName;
      String picsPath = servletContext.getRealPath("/upload");
      System.out.println("##debug: " + picsPath);
      File file = new File(picsPath + newName);
      dto.setOrgName(orgName);
      dto.setNewName(newName);
      dto.setRoomTypeNo(roomTypeNo);
      dto.setPicsPath("/upload");
      multi.transferTo(file);
      if (service.addRoomPics(dto)) {
        System.out.println("##debug: 객실사진업로드 성공");

      } else {
        System.out.println("##debug:  객실사진업로드 실패");
      }
    }
    mv.setViewName("room/selectRoom");
    return mv;
  }
Exemplo n.º 23
0
  /**
   * Example URL: http://localhost:8080/webstore/products/add
   *
   * <p>Called when a POST is requested
   *
   * @param newProduct
   * @return
   */
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String processAddNewProductForm(
      @ModelAttribute("newProduct") @Valid Product newProduct,
      BindingResult result,
      HttpServletRequest request) {
    if (result.hasErrors()) {
      return "addProduct";
    }

    String[] suppressedFields = result.getSuppressedFields();
    if (suppressedFields.length > 0) {
      throw new RuntimeException(
          "Attempting to bind disallowed fields: "
              + StringUtils.arrayToCommaDelimitedString(suppressedFields));
    }

    MultipartFile productImage = newProduct.getProductImage();
    MultipartFile productManual = newProduct.getProductManual();

    String rootDirectory = request.getSession().getServletContext().getRealPath("/");

    if (productImage != null && !productImage.isEmpty()) {
      try {
        productImage.transferTo(
            new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".jpg"));
      } catch (Exception e) {
        throw new RuntimeException("Product Image saving failed", e);
      }
    }

    if (productManual != null && !productManual.isEmpty()) {
      try {
        productManual.transferTo(
            new File(rootDirectory + "resources\\pdf\\" + newProduct.getProductId() + ".pdf"));
      } catch (Exception e) {
        throw new RuntimeException("Product Manual saving failed", e);
      }
    }

    productService.addProduct(newProduct);
    return "redirect:/products";
  }
Exemplo n.º 24
0
 @RequestMapping(value = "/upload")
 public String updateThumb(
     @RequestParam("name") String name, @RequestParam("file") MultipartFile file)
     throws Exception {
   if (!file.isEmpty()) {
     file.transferTo(new File("d:/temp/" + file.getOriginalFilename()));
     return "redirect:success.html";
   } else {
     return "redirect:fail.html";
   }
 }
Exemplo n.º 25
0
  @RequestMapping(value = "/hello/upload", method = RequestMethod.POST)
  public String upload(@RequestParam(value = "file") MultipartFile file, RedirectAttributes flash)
      throws IOException {

    if (!file.isEmpty()) {
      FileCopyUtils.copy(file.getBytes(), new File(file.getOriginalFilename() + ".pdf"));
    } else {
      flash.addFlashAttribute("error", "Error: the file is empty");
    }
    return "redirect:/hello";
  }
Exemplo n.º 26
0
  @RequestMapping(value = "/library/add", method = RequestMethod.POST)
  public String addLibrary(Model model, String doctype, int cate1, int cate2, MultipartFile doc) {

    System.out.println("file size : " + doc.getSize());

    if (!doc.isEmpty()) {
      docDao.saveFile(doctype, doc, cate1, cate2);
    }

    return "redirect:/admin/library/list";
  }
  /** {@inheritDoc} */
  @Override
  public void validate(final Object target, final Errors errors) {
    final FileUploadForm form = (FileUploadForm) target;
    final MultipartFile file = form.getFile();
    if (file.isEmpty()) {
      errors.rejectValue(WebKeys.FILE, "I0002");
      return;
    }

    if (StringUtils.isBlank(form.getPath())) {
      errors.rejectValue(WebKeys.PATH, "I0004");
    }
  }
Exemplo n.º 28
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";
    }
  }
Exemplo n.º 29
0
  @RequestMapping("/bulk-invite")
  public String bulkInvite(@RequestParam("invitees") MultipartFile invitees) throws Exception {
    if (!invitees.isEmpty()) {
      Map<String, InvitationGroup> groupsByName = new HashMap<String, InvitationGroup>();
      ViewQuery query =
          new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true);
      for (InvitationGroup existing : db.queryView(query, InvitationGroup.class)) {
        groupsByName.put(standardizeName(existing.getGroupName()), existing);
      }

      BufferedReader r = new BufferedReader(new InputStreamReader(invitees.getInputStream()));
      for (String row = r.readLine(); row != null; row = r.readLine()) {
        String[] cells = row.split(",");
        if (cells[0].equals("Group Name")) continue;
        if (!(StringUtils.hasText(cells[0])
            && StringUtils.hasText(cells[1])
            && StringUtils.hasText(cells[2]))) throw new RuntimeException("Malformed row: " + row);
        if (cells[0].startsWith("\"") && cells[0].endsWith("\""))
          cells[0] = cells[0].substring(1, cells[0].length() - 1);
        InvitationGroup group = groupsByName.get(cells[0].trim());
        if (group == null) {
          group = new InvitationGroup();
          group.setGroupName(cells[0].trim());
          throw new RuntimeException("Only updates now! Couldn't find " + cells[0]);
        }
        group.setEmail(cells[1].trim());
        group.setLanguage(cells[2].trim());
        group.setInvitedTours(StringUtils.hasText(cells[3]));
        group.setInvitedRehearsal(StringUtils.hasText(cells[4]));
        if (group.getInvitees() != null) group.getInvitees().clear();
        for (int i = 5; i < cells.length; ++i) {
          if (StringUtils.hasText(cells[i].trim())) {
            Invitee invitee = new Invitee();
            invitee.setName(cells[i].trim());
            group.addInvitee(invitee);
          }
        }
        if (group.getInvitees().size() == 0)
          throw new RuntimeException("Group with no invitees: " + row);
        if (group.getId() == null) {
          group.setId(randomId());
          db.create(group);
          System.out.println("Created " + group.getGroupName());
        } else {
          db.update(group);
          System.out.println("Updated " + group.getId() + " " + group.getGroupName());
        }
      }
    }
    return "redirect:admin";
  }
Exemplo n.º 30
0
 @RequestMapping(value = "/profile", params = "upload", method = RequestMethod.POST)
 public String onUpload(MultipartFile file, RedirectAttributes redirectAttrs, Model model)
     throws IOException {
   if (file.isEmpty() || !isImage(file)) {
     // throw new IOException("Incorrect file.Please upload a picture.");
     redirectAttrs.addFlashAttribute("error", "Incorrect file.Please upload a picture.");
     return "redirect:/profile";
   }
   // copyFileToPictures(file);
   Resource picturePath = copyFileToPictures(file);
   // model.addAttribute("picturePath", picturePath.getFile().toPath());
   userProfileSession.setPicturePath(picturePath);
   return "redirect:/profile";
 }