Example usage for org.springframework.web.multipart MultipartFile getBytes

List of usage examples for org.springframework.web.multipart MultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getBytes.

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:com.uwca.operation.modules.api.company.web.CompanyController.java

private void saveFile(String newFileName, MultipartFile filedata) {
    String saveFilePath = Global.getUserfilesBaseDir();
    File fileDir = new File(saveFilePath);
    if (!fileDir.exists()) {
        fileDir.mkdirs();/* w ww .  jav  a  2s .c  o  m*/
    }
    try {
        FileOutputStream out = new FileOutputStream(saveFilePath + File.separator + newFileName);
        out.write(filedata.getBytes());
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.glaf.mail.web.springmvc.MailTaskController.java

@RequestMapping("/uploadMails")
public ModelAndView uploadMails(HttpServletRequest request, ModelMap modelMap) {
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> params = RequestUtils.getParameterMap(req);
    logger.debug(params);/* www .  jav  a 2s  .  c o  m*/
    // System.out.println(params);
    String taskId = req.getParameter("taskId");
    if (StringUtils.isEmpty(taskId)) {
        taskId = req.getParameter("id");
    }
    MailTask mailTask = null;
    if (StringUtils.isNotEmpty(taskId)) {
        mailTask = mailTaskService.getMailTask(taskId);
    }

    if (mailTask != null && StringUtils.equals(RequestUtils.getActorId(request), mailTask.getCreateBy())) {

        try {
            Map<String, MultipartFile> fileMap = req.getFileMap();
            Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
            for (Entry<String, MultipartFile> entry : entrySet) {
                MultipartFile mFile = entry.getValue();
                if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                    logger.debug(mFile.getName());
                    if (mFile.getOriginalFilename().endsWith(".txt")) {
                        byte[] bytes = mFile.getBytes();
                        String rowIds = new String(bytes);
                        List<String> addresses = StringTools.split(rowIds);
                        if (addresses.size() <= 100000) {
                            mailDataFacede.saveMails(taskId, addresses);
                        } else {
                            throw new RuntimeException("mail addresses too many");
                        }
                        break;
                    }
                }
            }
        } catch (Exception ex) {// ?
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }
    return this.mailList(request, modelMap);
}

From source file:com.peadargrant.filecheck.web.controllers.CheckController.java

@RequestMapping(method = RequestMethod.POST)
public String performCheck(@RequestParam(value = "assignment", required = true) String assignmentCode,
        @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {

    String assignmentsUrl = serverEnvironment.getPropertyAsString("assignmentsUrl");
    model.addAttribute("assignmentsUrl", assignmentsUrl);

    // bail out if the file is empty
    if (file.isEmpty()) {
        model.addAttribute("message", "file.was.empty");
        return "error";
    }/*from   w  w w.j av  a2 s .  com*/

    // input stream from file 
    byte[] bytes = file.getBytes();
    String name = file.getOriginalFilename();

    // write to temp dir
    String filePath = System.getProperty("java.io.tmpdir") + "/" + name;
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
    stream.write(bytes);
    stream.close();

    // load file
    File inputFile = new File(filePath);

    // get assignment
    Assignment assignment = this.getAssignmentForCode(assignmentCode);
    if (assignment == null) {
        return "assignmentNotFound";
    }
    model.addAttribute(assignment);

    // GUI report table model
    SummaryTableModel summaryTableModel = new SummaryTableModel();
    ReportTableModel reportTableModel = new ReportTableModel(summaryTableModel);

    // checker
    Checker checker = new Checker();
    checker.setReport(reportTableModel);
    checker.runChecks(inputFile, assignment);

    // details for output
    model.addAttribute("fileName", name);
    model.addAttribute("startTime", new java.util.Date());
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    model.addAttribute("remoteIP", ipAddress);

    // final outcome
    model.addAttribute("outcome", summaryTableModel.getFinalOutcome());
    Color finalOutcomeColor = summaryTableModel.getFinalOutcome().getSaturatedColor();
    model.addAttribute("colourr", finalOutcomeColor.getRed());
    model.addAttribute("colourg", finalOutcomeColor.getGreen());
    model.addAttribute("colourb", finalOutcomeColor.getBlue());

    // transformer for parsing tables
    FileCheckWebTableTransformer transformer = new FileCheckWebTableTransformer();

    // summary table headings
    List<String> summaryColumns = transformer.getColumnHeaders(summaryTableModel);
    model.addAttribute("summaryColumns", summaryColumns);

    // summary table
    List summaryContents = transformer.getTableContents(summaryTableModel);
    model.addAttribute("summary", summaryContents);

    // detail table headings
    List<String> detailColumns = transformer.getColumnHeaders(reportTableModel);
    model.addAttribute("detailColumns", detailColumns);

    // detail report table
    List detailContents = transformer.getTableContents(reportTableModel);
    model.addAttribute("detail", detailContents);

    // delete the uploaded file
    inputFile.delete();

    // Return results display
    return "check";
}

From source file:de.hska.ld.core.service.impl.UserServiceImpl.java

@Override
public void uploadAvatar(MultipartFile file, String name) {
    try {/*  w  w w. j a  v  a 2 s .c o  m*/
        //String avatar = name + ";" + new String(file.getBytes());
        User user = Core.currentUser();
        user.setAvatar(file.getBytes());
        super.save(user);
    } catch (IOException e) {
        throw new ApplicationException();
    }
}

From source file:ts.service.FileUploadService.java

/**
 * Upload file/*from   w w w  .  ja  va  2  s  .c  o m*/
 *
 * @param file - saved file
 * @param user - current user
 */
public void uploadFileToS3(MultipartFile file, UserEntity user) {
    String fileLocation = null;
    String bucketName = user.getId().toHexString();
    S3Bucket fileBucket = null;
    try {
        // get or create bucket
        if (bucketName != null) {
            fileBucket = awsS3.getOrCreateBucket(bucketName);
        } else
            throw new UploadFileException("bucket cannot null");
        S3Object fileObject = new S3Object("profileImg");

        // set info file
        fileObject.setDataInputStream(new ByteArrayInputStream(file.getBytes()));
        fileObject.setContentLength(file.getBytes().length);
        fileObject.setContentType("image/jpeg");

        // get permissions
        AccessControlList acl = new AccessControlList();
        acl.setOwner(fileBucket.getOwner());
        acl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ);
        fileObject.setAcl(acl);

        // put file in bucket
        awsS3.putObject(fileBucket, fileObject);
        fileLocation = File.separator + fileBucket.getName() + File.separator + file.getOriginalFilename();
        //            DocumentEntity doc = new DocumentEntity(file.getOriginalFilename(), fileLocation, user);
        //            documentRepository.save(doc);
    } catch (S3ServiceException | IOException e) {
        LOG.error("Failed upload : ", e);
    }
}

From source file:controllers.SceneController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file,
        @RequestParam(value = "sceneId", required = true) Long sceneId, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//from www  . j  av  a2  s  .  c o m
        File newFile = new File("/usr/local/etc/sceneParamsList");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            sceneService.updateFromXml(newFile, sceneId);
            ras.addFlashAttribute("error", sceneService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("sceneId", sceneId);
    return "redirect:/Scene/show";
}

From source file:org.centralperf.controller.RunController.java

/**
 * Create a run and import result from JTL (CSV) file
 * @param projectId ID of the project (From URI)
 * @return Redirection to the run detail page
 *///from  w w w  . j  a  v a  2s  .com
@RequestMapping(value = "/project/{projectId}/run/import", method = RequestMethod.POST)
public String importRun(@PathVariable("projectId") Long projectId, @ModelAttribute("run") @Valid Run run,
        @RequestParam("jtlFile") MultipartFile file, BindingResult result, Model model) {
    if (result.hasErrors()) {
        model.addAttribute("newRun", run);
        return "redirect:/project/" + projectId + "/run";
    }

    // Get the jtl File
    try {
        String jtlContent = new String(file.getBytes());
        runService.importRun(run, jtlContent);
    } catch (IOException e) {
    }

    return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail";
}

From source file:com.goodhuddle.huddle.service.impl.ThemeServiceImpl.java

@Override
@Transactional(readOnly = false)/*from   w w w  .j a  va  2s. c  om*/
public Theme createThemeFromUpload(MultipartFile themeBundle, boolean activate) throws ThemeBundleException {
    try {
        log.info("Importing theme from zip file: {}", themeBundle.getOriginalFilename());

        String tempFileId = fileStore.createTempFile(themeBundle.getBytes());
        Theme theme = createThemeFromFile(fileStore.getTempFile(tempFileId), activate);
        fileStore.deleteTempFile(tempFileId);
        return theme;

    } catch (IOException e) {
        throw new ThemeBundleException("Error creating theme from bundle: " + themeBundle, e);
    }
}

From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java

@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/scoringRule/conversionTableFile/{type}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
@Secured({ "ROLE_Scoring Rule Modify" })
// NOTE: there is intentionally no @PreAuthorize annotation...ability to modify scoring rule is all that is needed since scoring rule conversion table files are non-tenanted
@ResponseBody/*from  w w w  . j av  a2  s  .  c o m*/
public String uploadConversionTableFile(
        @RequestParam("conversionTableFile") final MultipartFile conversionTableFile,
        @PathVariable("type") final String type, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    String jsonAsStringForIE = null;
    try {
        final GridFSFile savedFile = this.scoringRuleService.saveConversionTableFile(type,
                conversionTableFile.getOriginalFilename(), conversionTableFile.getBytes(),
                conversionTableFile.getContentType());
        jsonAsStringForIE = savedFile.toString();
    } catch (final LocalizedException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    } catch (final IOException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    }

    return jsonAsStringForIE;
}

From source file:org.literacyapp.web.content.multimedia.video.VideoCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Video video,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(video.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*from  w  ww  .jav  a2s .  c o  m*/
        Video existingVideo = videoDao.read(video.getTitle(), video.getLocale());
        if (existingVideo != null) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".m4v")) {
                video.setVideoFormat(VideoFormat.M4V);
            } else if (originalFileName.toLowerCase().endsWith(".mp4")) {
                video.setVideoFormat(VideoFormat.MP4);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (video.getVideoFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                video.setContentType(contentType);

                video.setBytes(bytes);

                // TODO: convert to a default video format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/video/create";
    } else {
        video.setTitle(video.getTitle().toLowerCase());
        video.setTimeLastUpdate(Calendar.getInstance());
        videoDao.create(video);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(video);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just added a new Video:\n" + " Language: "
                            + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle()
                            + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/video/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/"
                    + video.getId() + "." + video.getVideoFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/video/list";
    }
}