/** 功能:修改图片 */
 @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;
 }
 /** 功能:添加修改 */
 @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;
 }
  @Test
  public void testImportStudents_exception() throws Exception {

    // Given
    StudentDirectoryServiceImpl studentDirectoryService = new StudentDirectoryServiceImpl();

    Logger logger = mock(Logger.class);
    studentDirectoryService.setLogger(logger);

    StudentDAO studentDAO = mock(StudentDAO.class);
    studentDirectoryService.setStudentDAO(studentDAO);

    MultipartFile multipartFile = mock(MultipartFile.class);

    IOException exception = new IOException("This is a dummy IOException.");
    when(multipartFile.getInputStream()).thenThrow(exception);

    // When
    studentDirectoryService.importStudents(multipartFile);

    // Then
    ArgumentCaptor<String> errorCaptor = ArgumentCaptor.forClass(String.class);
    verify(logger, times(1)).error(errorCaptor.capture());

    assertEquals(exception, errorCaptor.getValue());
  }
  @Test
  public void testImportStudents() throws Exception {

    // Given
    StudentDirectoryServiceImpl studentDirectoryService = new StudentDirectoryServiceImpl();

    StudentDAO studentDAO = mock(StudentDAO.class);
    studentDirectoryService.setStudentDAO(studentDAO);

    MultipartFile multipartFile = mock(MultipartFile.class);

    StringBuffer buffer = new StringBuffer();
    buffer.append("Bart, Simpson\n");
    buffer.append("Lisa, Simpson");
    InputStream stream =
        new ByteArrayInputStream(buffer.toString().getBytes(StandardCharsets.UTF_8));
    when(multipartFile.getInputStream()).thenReturn(stream);

    // When
    studentDirectoryService.importStudents(multipartFile);

    // Then
    ArgumentCaptor<Student> studentCaptor = ArgumentCaptor.forClass(Student.class);
    verify(studentDAO, times(2)).createStudent(studentCaptor.capture());

    assertEquals("Bart", studentCaptor.getAllValues().get(0).getFirstName());
    assertEquals("Simpson", studentCaptor.getAllValues().get(0).getLastName());

    assertEquals("Lisa", studentCaptor.getAllValues().get(1).getFirstName());
    assertEquals("Simpson", studentCaptor.getAllValues().get(1).getLastName());
  }
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  public String save(
      @Valid @ModelAttribute("document") Document document,
      BindingResult result,
      @RequestParam("file") MultipartFile file) {

    if (result.hasErrors()) {
      return "doc/documents.tiles";
    }

    System.out.println("Name:" + document.getName());
    System.out.println("Desc:" + document.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());

    try {
      Blob blob = Hibernate.createBlob(file.getInputStream());

      document.setFilename(file.getOriginalFilename());
      document.setContent(blob);
      document.setContentType(file.getContentType());
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      documentService.save(document);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return "redirect:/doc/index";
  }
  // 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);
  }
  @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);
    }
  }
  private String saveUploadFile(MultipartFile file, String targetDir, String targetFilename) {
    if (file == null) {
      return null;
    }

    File dir = new File(targetDir);
    if (!dir.exists()) {
      log.info("dir {} not exists.create dir now.", dir.getAbsolutePath());
      dir.mkdirs();
    }
    try {
      String fileName = file.getOriginalFilename();
      log.debug("fileName:{}", fileName);
      InputStream is = file.getInputStream();
      try {
        byte[] fileBytes = IOUtils.toByteArray(is);
        FileUtils.writeByteArrayToFile(new File(targetDir + targetFilename), fileBytes);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
      } finally {
        IOUtils.closeQuietly(is);
      }
      return targetDir + targetFilename;
    } catch (IOException e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
Example #9
0
  // 统一的Excel上传导入方式
  @RequestMapping(params = "importExcel", method = RequestMethod.POST)
  @ResponseBody
  public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
    AjaxJson j = new AjaxJson();

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
      MultipartFile file = entity.getValue(); // 获取上传文件对象
      List<JpPersonEntity> listPersons;
      try {
        listPersons =
            ExcelImportUtil.importExcel(
                file.getInputStream(), JpPersonEntity.class, new ImportParams());
        for (JpPersonEntity person : listPersons) {
          if (person.getAge() != null) {
            person.setId(UUIDGenerator.generate());
            jpPersonService.save(person);
          }
        }
        j.setMsg("文件导入成功!");
      } catch (Exception e) {
        j.setMsg("文件导入失败!");
        logger.error(ExceptionUtil.getExceptionMessage(e));
      }
      // break; // 不支持多个文件导入?
    }

    return j;
  }
  // 编辑器上传图片
  @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;
  }
 public DeviceTestData parseAndSaveBBIFile(
     MultipartFile BBIfile, String verificationID, String originalFileName)
     throws IOException, NoSuchElementException, DecoderException {
   DeviceTestData deviceTestData =
       parseAndSaveBBIFile(BBIfile.getInputStream(), verificationID, originalFileName);
   return deviceTestData;
 }
  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());
    }
  }
Example #13
0
  @RequestMapping(value = "/uploadFiles")
  @ResponseBody
  public Result uploadFiles(HttpServletRequest request) throws IOException {
    MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request;
    List<MultipartFile> fileList = servletRequest.getFiles("uploadFile");
    if (fileList != null && fileList.size() > 0) {
      List<String> files = new ArrayList<String>();
      for (MultipartFile file : fileList) {
        if (file != null && file.getSize() > 0) {
          String realPath = request.getSession().getServletContext().getRealPath("/upload");
          String remotFilePath = FtpUtil.getFilePathName("file");
          String orgFileName = file.getOriginalFilename();
          String remortFileName = FtpUtil.getRemotFileName(orgFileName);
          String fileName =
              (new StringBuilder())
                  .append(remotFilePath)
                  .append("/")
                  .append(remortFileName)
                  .toString();
          FileUtils.copyInputStreamToFile(
              file.getInputStream(),
              new File(realPath + File.separator + remotFilePath, remortFileName));

          files.add(fileName);
        }
      }
      String dataJson = JSON.toJSONString(files);
      return Result.getSuccessResult(dataJson);
    }
    return new Result(ErrorCode.UPLOAD_FILE_FAILURE);
  }
  @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);
  }
  @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";
  }
Example #16
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;
 }
Example #17
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";
  }
  public FileUploadResponse uploadClientComponent(MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename();
    String className = fileName.substring(0, fileName.lastIndexOf(".zip"));
    FileUploadResponse ret = new FileUploadResponse();
    Folder componentStage =
        this.fileSystem
            .getWaveMakerHomeFolder()
            .getFolder("common/packages")
            .getFolder(CLIENT_COMPONENTS_STAGE);
    ZipArchive.unpack(file.getInputStream(), componentStage);
    com.wavemaker.tools.io.File jsFile =
        componentStage.getFile(className + "/" + className + ".js");
    if (!jsFile.exists()) {
      componentStage.delete();
      throw new IOException(jsFile.toString() + " not found");
    }
    String str = getClientComponentPackageString(jsFile);
    String packageStr = str.substring(0, str.lastIndexOf("." + className));

    Folder componentFolder =
        this.fileSystem
            .getWaveMakerHomeFolder()
            .getFolder(StringUtils.packageToSrcFilePath(packageStr));
    componentFolder.createIfMissing();
    componentFolder.list().delete(); // delete older version of the composite
    Folder zipFolder = componentStage.getFolder(className);
    zipFolder.copyContentsTo(componentFolder);
    this.deploymentManager.writeModuleToLibJs(packageStr + "." + className);
    componentStage.delete();
    ret.setPath(packageStr + "." + className);

    return ret;
  }
Example #19
0
 public void upload() throws Exception {
   MultipartRequest multipartRequest = (MultipartRequest) this.request;
   String currRelativeFolder = this.getFolder(this.relativeFolder);
   FileUtils.forceMkdir(new File(this.savePath + currRelativeFolder));
   MultipartFile multipartFile = multipartRequest.getFile("upfile");
   if (multipartFile == null) {
     this.state = ERROR_INFO.get("NOFILE");
     return;
   }
   if (multipartFile.getSize() > this.maxSize) {
     this.state = ERROR_INFO.get("SIZE");
     return;
   }
   this.originalName = multipartFile.getOriginalFilename();
   if (!this.checkFileType(this.originalName)) {
     this.state = ERROR_INFO.get("TYPE");
     return;
   }
   this.fileName = this.getName(this.originalName);
   this.type = this.getFileExt(this.originalName);
   this.url = currRelativeFolder + "/" + fileName;
   FileUtils.copyInputStreamToFile(
       multipartFile.getInputStream(),
       new File(savePath + currRelativeFolder + "/" + this.fileName));
   this.state = ERROR_INFO.get("SUCCESS");
   // UE中只会处理单张上传,完成后即退出
 }
Example #20
0
 @RequestMapping("/add")
 public ModelAndView add(@Valid ContentRequest request, BindingResult result) {
   MultipartFile image = request.getCoverImg();
   String path = StringUtils.EMPTY;
   if (image != null) {
     String fileType = FileUtil.getFileType(image.getOriginalFilename());
     String fileName =
         new StringBuilder().append(UUID.randomUUID()).append(".").append(fileType).toString();
     try {
       path = CDNUtil.uploadFile(image.getInputStream(), fileName);
     } catch (Exception e) {
       log.error("UploadFile Error.", e);
     }
   }
   Content content = new Content();
   content.setCoverImg(path);
   content.setAdminUserId(0L);
   content.setArticle(request.getArticle());
   content.setClicks(0L);
   Date time = new Date();
   content.setCreated(time);
   content.setUpdated(time);
   content.setStatus("inactive");
   content.setSynopsis(request.getSynopsis());
   content.setTitle(request.getTitle());
   content.setType(request.getType());
   contentDAO.save(content);
   return new ModelAndView("redirect:/content/detail/" + content.getId());
 }
  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();
          }
        }
      }
    }
  }
Example #22
0
 @RequestMapping("/edit/{contentId}")
 public ModelAndView edit(
     @PathVariable Long contentId, @Valid ContentRequest request, BindingResult result) {
   Content content = contentDAO.get(contentId);
   MultipartFile image = request.getCoverImg();
   if (image != null) {
     String fileType = FileUtil.getFileType(image.getOriginalFilename());
     String fileName =
         new StringBuilder().append(UUID.randomUUID()).append(".").append(fileType).toString();
     try {
       String path = CDNUtil.uploadFile(image.getInputStream(), fileName);
       content.setCoverImg(path);
     } catch (Exception e) {
       log.error("UploadFile Error.", e);
     }
   }
   content.setArticle(request.getArticle());
   content.setUpdated(new Date());
   content.setStatus(request.getStatus());
   content.setSynopsis(request.getSynopsis());
   content.setTitle(request.getTitle());
   content.setType(request.getType());
   contentDAO.update(content);
   return new ModelAndView("redirect:/content/detail/" + contentId);
 }
  /** {@inheritDoc} */
  @Multipart
  @RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.POST)
  @ResponseBody
  public VideoStatus setVideoData(
      @PathVariable(ID_PARAMETER) final long id,
      @RequestParam(DATA_PARAMETER) final MultipartFile videoData) {
    try {
      final InputStream is = videoData.getInputStream();
      Video v = new Video();
      v.setId(id);
      v.setDataUrl(VIDEO_DATA_PATH + id);
      boolean containsVideo = false;
      for (Video video : videoList) {
        if (video.getId() == id) {
          containsVideo = true;
        }
      }
      if (containsVideo) {
        VideoFileManager fileManager = VideoFileManager.get();
        fileManager.saveVideoData(v, is);

      } else {
        throw new ResourceNotFoundException();
      }

    } catch (final IOException e) {
      e.printStackTrace();
    }
    final VideoStatus status = new VideoStatus(VideoState.READY);
    return status;
  }
Example #24
0
 // 老的EasyUI上传方式(2013/05/28废弃)
 @RequestMapping(params = "implXls")
 @ResponseBody
 public AjaxJson implXls(HttpServletRequest request, HttpServletResponse response) {
   AjaxJson j = new AjaxJson();
   MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
   MultipartFile file = mulRequest.getFile("filedata");
   List<JpPersonEntity> listPersons;
   try {
     boolean isSuccess = true;
     listPersons =
         ExcelImportUtil.importExcel(
             file.getInputStream(), JpPersonEntity.class, new ImportParams());
     for (JpPersonEntity person : listPersons) {
       person.setId(UUIDGenerator.generate());
       if (person.getAge() == null || person.getCreatedt() == null || person.getSalary() == null) {
         isSuccess = false;
         break;
       } else {
         jpPersonService.save(person);
       }
     }
     if (isSuccess) j.setMsg("文件导入成功!");
     else j.setMsg("文件格式不正确,导入失败!");
   } catch (IOException e) {
     j.setMsg("文件导入失败!");
     logger.error(ExceptionUtil.getExceptionMessage(e));
   } catch (Exception e) {
     j.setMsg("文件格式不正确,导入失败!");
   }
   return j;
 }
  /**
   * 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);
  }
  /**
   * 엑셀파일을 업로드하여 우편번호를 등록한다.
   *
   * @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";
  }
 @Override
 public Blob createBlob(MultipartFile uploadedFile) throws IOException {
   Long size = uploadedFile.getSize();
   InputStream inputStream = uploadedFile.getInputStream();
   // We'll work with Blob instances and streams so that the uploaded files are never read into
   // memory
   return ((HibernateEntityManager) em).getSession().getLobHelper().createBlob(inputStream, size);
 }
Example #28
0
 /** @return */
 public InputStream getInputStream() {
   try {
     return multipartFile.getInputStream();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
 public List<BBIOutcomeDTO> parseAndSaveArchiveOfBBIfiles(
     MultipartFile archiveFile, String originalFileName, User calibratorEmployee)
     throws IOException, ZipException, SQLException, ClassNotFoundException, ParseException {
   List<BBIOutcomeDTO> resultsOfBBIProcessing =
       parseAndSaveArchiveOfBBIfiles(
           archiveFile.getInputStream(), originalFileName, calibratorEmployee);
   return resultsOfBBIProcessing;
 }
Example #30
0
  @RequestMapping(value = "/admin/speaker/{speakerId}", method = RequestMethod.POST)
  public String editSpeaker(
      @PathVariable("speakerId") Long speakerId,
      @RequestParam MultipartFile pictureFile,
      @Valid Speaker speakerForm,
      BindingResult result,
      HttpServletRequest request) {

    if (request.getParameter("cancel") != null) {
      return "redirect:/s/admin/index";
    }

    if (result.hasErrors()) {
      return "/admin/add-speaker";
    }

    final Speaker speakerFromDb = businessService.getSpeaker(speakerId);

    speakerFromDb.setBio(speakerForm.getBio());
    speakerFromDb.setTwitterId(speakerForm.getTwitterId());
    speakerFromDb.setGooglePlusId(speakerForm.getGooglePlusId());
    speakerFromDb.setFirstName(speakerForm.getFirstName());
    speakerFromDb.setLastName(speakerForm.getLastName());

    if (pictureFile != null && pictureFile.getSize() > 0) {

      final FileData pictureData;
      if (speakerFromDb.getPicture() == null) {
        pictureData = new FileData();
      } else {
        pictureData = speakerFromDb.getPicture();
      }

      try {

        pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream()));
        pictureData.setFileSize(pictureFile.getSize());
        pictureData.setFileModified(new Date());
        pictureData.setName(pictureFile.getOriginalFilename());
        pictureData.setType(pictureFile.getContentType());

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      speakerFromDb.setPicture(pictureData);

      String message = "File '" + pictureData.getName() + "' uploaded successfully";
      // FlashMap.setSuccessMessage(message);
    }

    businessService.saveSpeaker(speakerFromDb);

    // FlashMap.setSuccessMessage("The speaker was edited successfully.");
    return "redirect:/s/admin/speakers";
  }