예제 #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.";
    }
  }
예제 #2
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;
 }
  @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;
  }
  @RequestMapping(value = "/resource", method = RequestMethod.POST)
  @ResponseStatus(HttpStatus.OK)
  public void addContent(
      @RequestParam String type,
      @RequestParam String name,
      @RequestParam String language,
      @RequestParam(required = false) String value,
      @RequestParam(required = false) MultipartFile contentFile)
      throws CMSLiteException, IOException {
    if (isBlank(type)) {
      throw new CMSLiteException("Resource type is required");
    }

    if (isBlank(name)) {
      throw new CMSLiteException("Resource name is required");
    }

    if (isBlank(language)) {
      throw new CMSLiteException("Resource language is required");
    }

    switch (type) {
      case "string":
        if (isBlank(value)) {
          throw new CMSLiteException("Resource content is required");
        }

        if (cmsLiteService.isStringContentAvailable(language, name)) {
          throw new CMSLiteException(
              String.format("Resource %s in %s language already exists.", name, language));
        }

        cmsLiteService.addContent(new StringContent(language, name, value));
        break;
      case "stream":
        if (null == contentFile) {
          throw new CMSLiteException("Resource content is required");
        }

        if (cmsLiteService.isStreamContentAvailable(language, name)) {
          throw new CMSLiteException(
              String.format("Resource %s in %s language already exists.", name, language));
        }

        String checksum = md5Hex(contentFile.getBytes());
        String contentType = contentFile.getContentType();

        cmsLiteService.addContent(
            new StreamContent(
                language,
                name,
                ArrayUtils.toObject(contentFile.getBytes()),
                checksum,
                contentType));
        break;
      default:
    }
  }
  @RequestMapping(value = "/resource/stream/{language}/{name}", method = RequestMethod.POST)
  @ResponseStatus(HttpStatus.OK)
  public void editStreamContent(
      @PathVariable String language,
      @PathVariable String name,
      @RequestParam MultipartFile contentFile)
      throws ContentNotFoundException, CMSLiteException, IOException {
    StreamContent streamContent = cmsLiteService.getStreamContent(language, name);

    streamContent.setChecksum(md5Hex(contentFile.getBytes()));
    streamContent.setContentType(contentFile.getContentType());
    streamContent.setContent(ArrayUtils.toObject(contentFile.getBytes()));

    cmsLiteService.addContent(streamContent);
  }
예제 #6
0
 public static File createFile(MultipartFile multipartFile) throws IOException {
   String fileName = generateFileName(multipartFile);
   String contentType = generateContentType(multipartFile);
   byte[] source = multipartFile.getBytes();
   File file = new File(source, contentType, fileName);
   return file;
 }
예제 #7
0
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public ResponseEntity<?> addBook(
      Principal principal,
      @RequestParam("title") String title,
      @RequestParam("intro") String intro,
      @RequestParam("categories") String[] categories,
      @RequestParam("file") MultipartFile file) {

    BookDTO bookDTO = new BookDTO(title, intro, file, categories);

    Set<ConstraintViolation<BookDTO>> violations =
        Validation.buildDefaultValidatorFactory().getValidator().validate(bookDTO);

    if (violations.size() > 0 || !file.getContentType().equals("application/pdf"))
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

    Book book = new Book();
    book.setTitle(title);
    book.setIntroduction(intro);
    book.setCategories(categories);
    try {
      book.setContent(file.getBytes());
    } catch (IOException e) {
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    book.setPublished_date(new Date());
    book.setTotal_pages(100);

    book.setUser(userRepo.findOneByEmail(principal.getName()));

    if (bookRepo.addBook(book) && bookRepo.addBookHasCategory(book))
      return new ResponseEntity<>(HttpStatus.ACCEPTED);
    else return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  }
예제 #8
0
  public String fileUploadClient(MultipartFile mpf) {

    String filePath = "";
    Client client = Client.create();
    WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/upload");
    byte[] logo = null;

    try {
      // logo = FileUtils.readFileToByteArray(file);
      logo = mpf.getBytes();
    } catch (IOException e1) {

      e1.printStackTrace();
    }

    // Construct a MultiPart with two body parts
    MultiPart multiPart =
        new MultiPart().bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE));

    // POST the request
    try {
      ClientResponse response =
          webResource.type("multipart/mixed").post(ClientResponse.class, multiPart);
      filePath = response.getEntity(String.class);

      System.out.println("id is " + filePath);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return filePath;
  }
예제 #9
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 = "/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.";
    }
  }
예제 #11
0
  public ModelAndView savePice(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    ModelAndView mv = new ModelAndView("./zswap/first");
    String msg = "";

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    MultipartFile imgFile1 = multipartRequest.getFile("sfz");
    byte[] fileBytes = imgFile1.getBytes();
    System.out.println(imgFile1.getSize() + "============size");
    if (imgFile1.getSize() > 1256000L) {
      msg = "上传图片不能大于1M!,请压缩图片后再上传!";
      mv.addObject("resultMsg", msg);
      return mv;
    }
    String URL = System.getProperty("user.dir") + "/update/" + new Date().getTime() + ".jpg";
    File file = new File(URL);

    FileOutputStream fos = new FileOutputStream(file);

    fos.write(fileBytes, 0, fileBytes.length);

    fos.flush();

    fos.close();
    System.out.println(URL);
    mv.addObject("resultMsg", msg);
    return mv;
  }
예제 #12
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();
      }
    }
  }
예제 #13
0
  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public boolean insertGame(RegisterGamePara registerGamePara) throws Exception {

    int intResult = 0;

    MultipartFile file = registerGamePara.getUpfile();
    String strName = file.getOriginalFilename();
    byte[] byteName = file.getBytes();

    logger.info("gameId >> " + registerGamePara.getGameId());
    logger.info("gameDomain >> " + registerGamePara.getGameDomain());
    logger.info("gameTitle >> " + registerGamePara.getGameTitle());
    logger.info("gameExplain >> " + registerGamePara.getGameExplain());

    Map<String, Object> mapRegisterGame = new HashMap<String, Object>();
    mapRegisterGame.put("gameId", registerGamePara.getGameId());
    mapRegisterGame.put("gameDomain", registerGamePara.getGameDomain());
    mapRegisterGame.put("gameTitle", registerGamePara.getGameTitle());
    mapRegisterGame.put("gameExplain", registerGamePara.getGameExplain());
    mapRegisterGame.put("gameFile", byteName);
    mapRegisterGame.put("gameStatusFlag", "0");

    try {
      intResult = masterAdminDao.getMapper(MasterAdminDao.class).insertGame(mapRegisterGame);
    } catch (Exception e) {
      logger.error("Exception error", e);
    }
    if (intResult < 1) {
      logger.error("InsertGame error, gameId={}", registerGamePara.getGameId());
      return false;
    }

    return true;
  }
예제 #14
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;
  }
예제 #15
0
  private void saveFileToLocalDisk(MultipartFile multipartFile)
      throws IOException, FileNotFoundException {

    String outputFileName = getOutputFilename(multipartFile);

    FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName));
  }
예제 #16
0
  /** Upload multiple file using Spring Controller */
  @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
  public @ResponseBody String uploadMultipleFileHandler(
      @RequestParam("name") String[] names, @RequestParam("file") MultipartFile[] files) {

    if (files.length != names.length) return "Mandatory information missing";

    String message = "";
    for (int i = 0; i < files.length; i++) {
      MultipartFile file = files[i];
      String name = names[i];
      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");
        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());

        message = message + "You successfully uploaded file=" + name + "<br />";
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    }
    return message;
  }
예제 #17
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.";
    }
  }
예제 #18
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 + "";
  }
  /**
   * @override @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors) {
    OtmlFileUpload bean = (OtmlFileUpload) command;
    MultipartFile file = bean.getFile();

    if (file == null) {
      ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));
      return modelAndView;
    } else {
      CreateOtmlModuleParameters params = new CreateOtmlModuleParameters();
      params.setName(bean.getName());
      params.setUrl(RooloOtmlModuleDao.defaultOtrunkCurnitUrl);
      params.setRetrieveotmlurl(
          Util.getPortalUrl(request) + "/repository/retrieveotml.html?otmlModuleId=");
      try {
        params.setOtml(file.getBytes());
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
      curnitService.createCurnit(params);
    }
    return null;
  }
예제 #20
0
  /**
   * 上传文件
   *
   * @param multipartFile
   * @param request
   */
  @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
  @ResponseBody
  public Map<String, String> fileUpload(MultipartFile multipartFile, HttpServletRequest request) {
    Map<String, String> map = new HashMap<>();
    map.put("msg", "上传失败");
    String path =
        request.getSession().getServletContext().getRealPath("/")
            + File.separator
            + "upload"
            + File.separator
            + multipartFile.getOriginalFilename();
    try {
      FileOutputStream fos = new FileOutputStream(path);
      fos.write(multipartFile.getBytes());
      fos.close();

      System.out.println("upload:" + path);
      map.put("msg", "上传成功");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return map;
  }
  /*
   @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";
  }
예제 #22
0
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public String uploadFile(@RequestParam("uploadFile") MultipartFile multipartFile)
      throws IOException {
    // ファイル名
    String fileName = multipartFile.getOriginalFilename();
    // ファイルの大きさ(単位はbyte)
    long size = multipartFile.getSize();
    // コンテンツタイプ
    String contentType = multipartFile.getContentType();
    // 内容(byte配列)
    byte[] fileContents = multipartFile.getBytes();

    // ファイルとして保存
    multipartFile.transferTo(new File("/tmp/" + fileName));

    InputStream is = null;
    try {
      // ファイルの内容を読み込むためのInputStream
      is = multipartFile.getInputStream();

      // InputStreamを使用した処理
    } finally {
      // 必ずcloseする
      is.close();
    }

    LOG.trace("size=" + size);
    LOG.trace("contentType=" + contentType);
    LOG.trace("fileContents=" + new String(fileContents, "UTF-8"));

    return "redirect:/upload";
  }
  @RequestMapping(method = RequestMethod.POST)
  public String addNewPost(
      WallPost wallPost,
      BindingResult result,
      HttpServletRequest request,
      @RequestParam(value = "holler") MultipartFile file) {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("loggedUser");
    wallPost.setAudioFileName(file.getOriginalFilename());
    wallPost.setAudioContentType(file.getContentType());
    wallPost.setPostBy(user);
    wallPost.setPostTo(user);
    wallPost.setDate(new Date());
    try {
      wallPost.setAudioContent(file.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
    postValidator.validate(wallPost, result);
    if (!result.hasErrors()) {
      postService.saveNewPost(wallPost);
    }

    return "redirect:/posts";
  }
  @RequestMapping(value = "/saveFriendsPost/{id}", method = RequestMethod.POST)
  public String saveFriendsPost(
      WallPost wallPost,
      BindingResult result,
      HttpServletRequest request,
      @PathVariable(value = "id") int friendId,
      @RequestParam(value = "holler") MultipartFile file) {
    User postBy = (User) request.getSession().getAttribute("loggedUser");
    User postTo = userService.getUser(friendId);
    wallPost.setPostTo(postTo);
    wallPost.setPostBy(postBy);
    wallPost.setDate(new Date());
    wallPost.setAudioContentType(file.getContentType());
    wallPost.setAudioFileName(file.getOriginalFilename());
    try {
      wallPost.setAudioContent(file.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
    postValidator.validate(wallPost, result);
    if (!result.hasErrors()) {
      log.debug("Saved the wall Post" + wallPost.getPostContent());
      postService.saveNewPost(wallPost);
    }

    if (request.getSession().getAttribute("friend") != null) {
      User friend = (User) request.getSession().getAttribute("friend");
      String id = Integer.toString(friend.getUserId());
      request.getSession().setAttribute("friend", null);
      return "redirect:/friends/showFullProfile/" + id;
    } else {
      return "redirect:/posts";
    }
  }
예제 #25
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;
  }
예제 #26
0
  /**
   * ************************************************* URL: /rest/controller/upload upload():
   * receives files
   *
   * @param request : MultipartHttpServletRequest auto passed
   * @param response : HttpServletResponse auto passed
   * @return LinkedList<FileMeta> as json format **************************************************
   */
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody LinkedList<FileMeta> upload(
      MultipartHttpServletRequest request, HttpServletResponse response) {

    // 1. build an iterator
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    String basePath = "f:/var/lirantest";
    new File(basePath).mkdirs();

    // 2. get each file
    while (itr.hasNext()) {

      // 2.1 get next MultipartFile
      mpf = request.getFile(itr.next());
      System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());

      // 2.2 if files > 10 remove the first from the list
      if (files.size() >= 10) files.pop();

      // 2.3 create new fileMeta
      fileMeta = new FileMeta();
      fileMeta.setFileName(mpf.getOriginalFilename());
      fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
      fileMeta.setFileType(mpf.getContentType());

      try {
        fileMeta.setBytes(mpf.getBytes());

        // copy file to local disk (make sure the path
        // "e.g. D:/temp/files" exists)
        FileCopyUtils.copy(
            mpf.getBytes(), new FileOutputStream(basePath + "/" + mpf.getOriginalFilename()));

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      // 2.4 add to files
      files.add(fileMeta);
    }

    // result will be like this
    // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
    return files;
  }
  @RequestMapping(
      value = "/workspace/trade-union-activists/update-event-images",
      method = RequestMethod.POST,
      produces = "text/plain; charset=utf-8")
  public String getUpdateEventImg(
      @ModelAttribute("uploadForm") FileUploadForm uploadForm,
      ModelMap map,
      @RequestParam String eventId,
      @RequestParam(required = false) String[] idPictures) {

    EventEntity eventEntity = eventService.findById(eventId);

    Set<ImageEntity> imageEntityList = new HashSet<>();

    if (null != idPictures) {
      imageEntityList = eventService.deleteFromEventsImage(eventEntity, idPictures);
    }

    byte fileBytes[];
    FileOutputStream fos = null;
    List<MultipartFile> list = uploadForm.getFiles();
    List<String> filenames = new ArrayList<>();
    if (list != null && list.size() > 0) {
      for (MultipartFile multipartFile : list) {
        final String fileName = multipartFile.getOriginalFilename();
        String webappRoot = servletContext.getRealPath("/");
        final String relativeFolder =
            "/resources" + File.separator + "img" + File.separator + "files" + File.separator;
        String path = webappRoot + relativeFolder + fileName;

        if (checkFormatFileUtils.checkingForImage(fileName)) {
          ImageEntity imageEntity =
              new ImageEntity() {
                {
                  setIdImage(Utils.generateIdentifier());
                  setPathToTheFileSystem(relativeFolder + fileName);
                }
              };
          imageEntityList.add(imageEntity);
        }
        try {
          fos = new FileOutputStream(new File(path));
          fileBytes = multipartFile.getBytes();
          fos.write(fileBytes);
          filenames.add(fileName);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    if (null != imageEntityList) {
      eventEntity.setEventImages(imageEntityList);
    }
    eventService.update(eventEntity);
    map.addAttribute("textPage", ActionMessage.READ_EVENT);
    return "pages/general/success-template-page";
  }
  @Test
  public void shouldReturnDefaultFormOnErrorWhenUpdatingAvatarUrl() throws Exception {
    setUpPlayerProfile();
    MultipartFile multipartFile = mock(MultipartFile.class);
    when(multipartFile.getBytes()).thenThrow(new IOException());

    assertMainProfilePageViewName(
        underTest.updateUserAvatar(request, response, false, multipartFile, modelMap));
  }
예제 #29
0
 private String getContentFromFile(MultipartFile contentFile) {
   try {
     String charset = Constants.ENCODE;
     final String content = new String(contentFile.getBytes(), charset);
     return content;
   } catch (Exception e) {
     throw new ConfigServiceException(e);
   }
 }
예제 #30
0
  @RequestMapping(method = RequestMethod.POST)
  public String upload(@RequestParam("file") MultipartFile file) throws Exception {
    InputStream inputStream = new ByteArrayInputStream(file.getBytes());

    if ("application/x-gzip".equals(file.getContentType()))
      inputStream = new GZIPInputStream(inputStream);

    String identifier = validatorService.validateWorkspace(inputStream);

    return "redirect:/v/" + identifier;
  }