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.springsource.hq.plugin.tcserver.serverconfig.web.controllers.HomeController.java

/**
 * Upload a file to tc Runtime./*www  .j ava 2  s.c om*/
 * 
 * @param model
 * @param settingsId the tc Runtime instance
 * @param file the server.xml file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/{settingsId}/upload/", method = RequestMethod.POST)
public String uploadConfigurationFile(Model model, @PathVariable("settingsId") String settingsId,
        @RequestParam("fileName") String fileName, @RequestParam("file") MultipartFile file)
        throws IOException {
    try {
        if (!uploadableFiles.contains(fileName)) {
            throw new UnsupportedOperationException("File " + fileName + " is not supported for uploading");
        }
        settingsService.uploadConfigurationFile(settingsId, fileName,
                new String(Base64.encodeBase64(file.getBytes())));
        model.addAttribute("message", "saved-to-server");
        return "redirect:/app/" + UriUtils.encodePathSegment(settingsId, "UTF-8") + "/";
    } catch (Exception e) {
        model.addAttribute("error", e.getMessage());
        model.addAttribute("settings", settingsService.loadSettings(settingsId));
        model.addAttribute("changePending", settingsService.isChangePending(settingsId));
        model.addAttribute("restartPending", settingsService.isRestartPending(settingsId));
        return "home/home";
    }
}

From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@Atomic
public AcademicServiceRequestTemplate createAcademicServiceRequestTemplate(LocalizedString name,
        LocalizedString description, java.util.Locale language, ServiceRequestType serviceRequestType,
        MultipartFile documentTemplateFile) throws IOException {
    AcademicServiceRequestTemplate academicServiceRequestTemplate = AcademicServiceRequestTemplate
            .createCustom(name, description, language, serviceRequestType);
    DocumentTemplateFile.create(academicServiceRequestTemplate, documentTemplateFile.getOriginalFilename(),
            documentTemplateFile.getBytes());
    return academicServiceRequestTemplate;
}

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

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String handleSubmit(HttpSession session, 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 w  w .ja v  a  2s  .  co m*/
        Video existingVideo = videoDao.read(video.getTitle(), video.getLocale());
        if ((existingVideo != null) && !existingVideo.getId().equals(video.getId())) {
            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("video", video);
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(video));
        return "content/multimedia/video/edit";
    } else {
        video.setTitle(video.getTitle().toLowerCase());
        video.setTimeLastUpdate(Calendar.getInstance());
        video.setRevisionNumber(Integer.MIN_VALUE);
        videoDao.update(video);

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

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

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just edited an 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";
    }
}

From source file:it.geosolutions.opensdi.service.impl.FileUploadServiceImpl.java

/**
 * Add a chunk of a file upload/*w  w w . ja v  a2 s . c o m*/
 * 
 * @param name of the file
 * @param chunks total for the file
 * @param chunk number on this upload
 * @param file with the content uploaded
 * @return current list of byte arrays for the file
 * @throws IOException if no more uploads are available
 */
public Entry<String, List<String>> addChunk(String name, int chunks, int chunk, MultipartFile file)
        throws IOException {
    Entry<String, List<String>> entry = null;
    try {
        entry = getChunk(name, chunks, chunk);
        if (LOGGER.isTraceEnabled())
            LOGGER.trace("entry [" + entry.getKey() + "] found ");
        List<String> uploadedChunks = entry.getValue();
        String tmpFile = createTemporalFile(entry.getKey(), file.getBytes(), entry.getValue().size());
        // add chunk on its position
        uploadedChunks.add(chunk, tmpFile);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("uploadedChunks size[" + entry.getKey() + "] --> " + uploadedChunks.size());
        }
    } catch (IOException e) {
        LOGGER.error("Error on file upload", e);
    }

    return entry;
}

From source file:com.vtxii.smallstuff.etl.fileuploader.FileUploaderController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (false == file.isEmpty()) {
        try {/*from   w w  w.jav a 2 s .  c om*/
            // See if the file exists. If it does then another user
            // has uploaded a file of the same name at the same time
            // and it has not yet been processed.
            File newFile = new File(name);
            if (true == newFile.exists()) {
                String msg = "fail: file \"" + name + "\" exists and hasn't been processed";
                logger.error(msg);
                return msg;
            }

            // Write the file (this should be to the landing directory)
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
            stream.write(bytes);
            stream.close();

            // Process the file
            LandingManager.process(newFile, processor, null);

            return "success: loaded " + name;
        } catch (Exception e) {
            String msg = "fail: file \"" + name + "\" with error " + e.getMessage();
            logger.error(msg);
            return msg;
        }
    } else {
        return "fail: file \"" + name + "\" empty";
    }
}

From source file:net.przemkovv.sphinx.web.TaskSolutionController.java

private Set<File> acquireFiles(MultipartHttpServletRequest request) throws IOException {
    Set<File> files = new HashSet<>();
    //1. build an iterator
    Iterator<String> itr = request.getFileNames();
    List<MultipartFile> multipartFiles = null;
    //2. get each file
    while (itr.hasNext()) {

        //2.1 get next MultipartFile
        multipartFiles = request.getFiles(itr.next());

        for (MultipartFile multipartFile : multipartFiles) {
            if (multipartFile.getSize() == 0)
                continue;
            ;/*w w w .  ja  v a  2 s.c  o  m*/
            logger.debug("{} uploaded! ", multipartFile.getOriginalFilename());

            //2.3 create new fileMeta
            File fileMeta = new File();
            fileMeta.setName(multipartFile.getOriginalFilename());
            fileMeta.setSize(multipartFile.getSize());
            fileMeta.setMimeType(multipartFile.getContentType());

            fileMeta.setContent(multipartFile.getBytes());
            //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;
}

From source file:com.google.ie.web.controller.ProjectController.java

/**
 * @param projectKey// w w  w  .  j  a  v  a  2  s .  c  o m
 * @param logoFile
 * @param projectDetail
 * @throws IOException
 */
private void uploadLogo(String projectKey, MultipartFile logoFile, ProjectDetail projectDetail)
        throws IOException {
    if (logoFile != null && logoFile.getBytes().length > 0) {
        try {
            Blob file = new Blob(logoFile.getBytes());
            projectDetail.getProject().setLogo(file);
        } catch (IOException e) {
            logger.error("couldn't find an Image at " + logoFile, e);
        }
    } else {
        Project project1 = new Project();
        if (projectService.getProjectById(projectKey) != null)
            project1 = projectService.getProjectById(projectKey);
        if (project1.getLogo() != null && project1.getLogo().getBytes().length > 0) {
            Blob file = new Blob(project1.getLogo().getBytes());
            projectDetail.getProject().setLogo(file);
        }
    }
}

From source file:com.tela.pms.PatientController.java

public File convertFile(MultipartFile file) throws IOException {
    File convFile = new File(file.getOriginalFilename());
    convFile.createNewFile();/*from   w  w  w  . ja  va2 s .co  m*/
    FileOutputStream fos = new FileOutputStream(convFile);
    fos.write(file.getBytes());
    fos.close();
    return convFile;
}

From source file:belajar.nfc.controller.CustomerController.java

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public void saveCustomer(@PathVariable String id, @RequestParam("foto") MultipartFile multipartFile,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Customer customer = findOne(id);/*from w  w w . java2 s . c  o  m*/

    if (customer == null)
        customer = new Customer();

    customer.setNama(request.getParameter("nama"));
    customer.setAlamat(request.getParameter("alamat"));
    customer.setEmail(request.getParameter("email"));
    String customerDate = request.getParameter("tanggalLahir");
    SimpleDateFormat formatDdate = new SimpleDateFormat("yyyy-MM-dd");
    Date date = formatDdate.parse(customerDate);
    customer.setTanggalLahir(date);

    byte[] buf = multipartFile.getBytes();
    customer.setFoto(buf);
    customerDao.save(customer);
}

From source file:io.onedecision.engine.decisions.web.DecisionDmnModelController.java

/**
 * Upload DMN representation of decision.
 * //  w w w  . java  2  s  . c  om
 * @param files
 *            DMN files posted in a multi-part request and optionally an
 *            image of it.
 * @return The model created in the repository.
 * @throws IOException
 *             If cannot parse the file.
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody DmnModel handleFileUpload(@PathVariable("tenantId") String tenantId,
        @RequestParam(value = "deploymentMessage", required = false) String deploymentMessage,
        @RequestParam(value = "file", required = true) MultipartFile... files) throws IOException {
    LOGGER.info(String.format("Uploading dmn for: %1$s", tenantId));

    if (files.length > 2) {
        throw new IllegalArgumentException(String
                .format("Expected one DMN file and optionally one image file but received %1$d", files.length));
    }

    String dmnContent = null;
    String dmnFileName = null;
    byte[] image = null;
    for (MultipartFile resource : files) {
        LOGGER.debug(String.format("Deploying file: %1$s", resource.getOriginalFilename()));
        if (resource.getOriginalFilename().toLowerCase().endsWith(".dmn")
                || resource.getOriginalFilename().toLowerCase().endsWith(".dmn.xml")) {
            LOGGER.debug("... DMN resource");
            dmnContent = new String(resource.getBytes(), "UTF-8");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("DMN: " + dmnContent);
            }
            dmnFileName = resource.getOriginalFilename();
        } else {
            LOGGER.debug("... non-DMN resource");
            image = resource.getBytes();
        }
    }

    if (dmnContent == null) {
        throw new NoDmnFileInUploadException();
    }
    if (deploymentMessage == null || deploymentMessage.length() == 0) {
        deploymentMessage = String.format("Deployed from file: %1$s", dmnFileName);
    }
    DmnModel dmnModel = new DmnModel(dmnContent, deploymentMessage, image, tenantId);
    dmnModel.setName(IdHelper.toName(dmnFileName));
    dmnModel.setDefinitionXml(dmnContent);
    return createModelForTenant(dmnModel);
}