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:pt.ist.fenix.ui.spring.AnnouncementsAdminController.java

@Atomic
private GroupBasedFile addFile(MultipartFile attachment, Post p) throws IOException {
    GroupBasedFile f = new GroupBasedFile(attachment.getOriginalFilename(), attachment.getOriginalFilename(),
            attachment.getBytes(), AnyoneGroup.get());
    p.getPostFiles().putFile(f);/*  w  w w.  j a  v a 2 s . c  o m*/
    return f;
}

From source file:com.card.loop.xyz.controller.LearningElementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("title") String title, @RequestParam("author") String author,
        @RequestParam("subject") String subject, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file, @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {/* w  w  w  .  j  av  a2  s. c om*/
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.USER_VARIABLE + AppConfig.LE_FILE_PATH + file.getOriginalFilename());

            if (!fil.getParentFile().exists()) {
                fil.getParentFile().mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningElement le = new LearningElement();
            le.setTitle(title);
            le.setUploadedBy(author);
            le.setDescription(description);
            le.setDownloads(0);
            le.setStatus(1);
            le.setRating(1);
            le.setUploadDate(new Date());
            le.setSubject(subject);
            le.setFilePath(AppConfig.LE_FILE_PATH);
            le.setFilename(file.getOriginalFilename());
            le.setContentType(file.getOriginalFilename().split("\\.")[1]);
            dao.addLearningElement(le);

            System.out.println("UPLOAD LE FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }
    return new ModelAndView("developer-le-loop-redirect");
}

From source file:org.ktunaxa.referral.server.mvc.UploadGeometryController.java

@RequestMapping(value = "/upload/referral/geometry", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam(KtunaxaConstant.FORM_ID) String formId,
        @RequestParam("file") MultipartFile file, Model model) {

    UploadResponse response = new UploadResponse();
    response.addObject(KtunaxaConstant.FORM_ID, formId);
    try {//from   ww w  . j a  va  2  s .c  o  m
        URL url = unzipShape(file.getBytes());
        ShapefileDataStore dataStore = new ShapefileDataStore(url);
        Geometry geometry = transform(getGeometry(dataStore),
                dataStore.getFeatureSource().getSchema().getCoordinateReferenceSystem());
        response.addObject(KtunaxaConstant.FORM_GEOMETRY, geometry.toText());
    } catch (Exception e) {
        log.error("Could not extract geometry", e);
        response.setException(e);
    }
    cleanup();
    model.addAttribute(UploadView.RESPONSE, response);
    return UploadView.NAME;
}

From source file:org.zols.documents.service.DocumentService.java

/**
 * Upload documents//  ww  w . j  a  v a2 s. c  om
 *
 * @param documentRepositoryName name of the repository
 * @param upload documents to be uploaded
 * @param rootFolderPath source path of the document
 */
public void upload(String documentRepositoryName, Upload upload, String rootFolderPath)
        throws DataStoreException {
    DocumentRepository documentRepository = documentRepositoryService.read(documentRepositoryName);
    String folderPath = documentRepository.getPath();
    if (rootFolderPath != null && rootFolderPath.trim().length() != 0) {
        folderPath = folderPath + File.separator + rootFolderPath;
    }
    List<MultipartFile> multipartFiles = upload.getFiles();
    if (null != multipartFiles && multipartFiles.size() > 0) {
        for (MultipartFile multipartFile : multipartFiles) {
            //Handle file content - multipartFile.getInputStream()
            byte[] bytes;
            try {
                bytes = multipartFile.getBytes();

                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                        new File(folderPath + File.separator + multipartFile.getOriginalFilename())));
                stream.write(bytes);
                stream.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(DocumentService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.github.wxiaoqi.oss.controller.OssController.java

/**
 * //from  ww w . j a  va  2  s.  com
 */
@RequestMapping("/upload")
public ObjectRestResponse<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
    if (file.isEmpty()) {
        throw new BaseException("?");
    }
    //
    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String url = ossFactory.build().uploadSuffix(file.getBytes(), suffix);
    return new ObjectRestResponse<>().data(url);
}

From source file:com.xumpy.timesheets.controller.pages.TimesheetsCtrl.java

@RequestMapping(value = "timesheets/saveSQLite")
public String saveSQLiteDB(@RequestParam("file") MultipartFile file) throws IOException {
    if (!file.isEmpty()) {
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File("/tmp/timeRecording.db")));
        stream.write(file.getBytes());
        stream.close();/* w w w.jav  a 2s  .c  om*/
    }

    return "redirect:/timesheets/importTimeRecordings";
}

From source file:com.zuoxiaolong.niubi.job.console.controller.StandbyJobController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ExceptionForward("/standbyJobSummaries")
public String upload(String packagesToScan, @RequestParam MultipartFile jobJar) {
    AssertHelper.notNull(jobJar, "jobJar can't be null.");
    AssertHelper.notEmpty(packagesToScan, "packagesToScan can't be empty.");
    String jarFilePath = getDirectoryRealPath("job/standby") + "/" + jobJar.getOriginalFilename();
    try {/*from w w w.  j a  v  a  2 s  . c o m*/
        IOHelper.writeFile(jarFilePath, jobJar.getBytes());
        standbyJobService.saveJob(jarFilePath, packagesToScan);
    } catch (IOException e) {
        throw new NiubiException(e);
    }
    return "forward:/standbyJobSummaries";
}

From source file:alpha.portal.webapp.controller.CardFileUploadController.java

/**
 * handles the case, if the user clicks on one of the buttons.
 * /*  ww  w  .  j a  va2  s. c o m*/
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return success view
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws IOException {

    final String caseId = request.getParameter("case");
    final String cardId = request.getParameter("card");
    final Locale locale = request.getLocale();

    this.setCancelView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);
    this.setSuccessView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);

    final AlphaCard card = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    if (card == null) {
        this.saveError(request, this.getText("card.invalidId", locale));
        return this.getCancelView();
    }
    final Adornment contributor = card.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());

    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {

        this.saveError(request, this.getText("adornment.noAccess", locale));
        return this.getCancelView();

    } else {

        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());

        if (contributorID != currentUser.getId()) {

            this.saveError(request, this.getText("adornment.noAccess", locale));
            return this.getCancelView();
        }
    }

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        fileUpload.setName("alphaCardPayloadFile");

        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile file = multipartRequest.getFile("file");

    Payload payload = new Payload(file.getOriginalFilename(), file.getContentType());
    payload.setContent(file.getBytes());

    payload = this.payloadManager.saveNewPayload(payload, card);

    this.saveMessage(request, this.getText("card.payloadOK", locale));
    return this.getSuccessView();
}

From source file:com.zuoxiaolong.niubi.job.console.controller.MasterSlaveJobController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ExceptionForward("/masterSlaveJobSummaries")
public String upload(String packagesToScan, @RequestParam MultipartFile jobJar) {
    AssertHelper.notNull(jobJar, "jobJar can't be null.");
    AssertHelper.notEmpty(packagesToScan, "packagesToScan can't be empty.");
    String jarFilePath = getDirectoryRealPath("job/masterSlave") + "/" + jobJar.getOriginalFilename();
    try {//from www.  j  av a 2 s. c om
        IOHelper.writeFile(jarFilePath, jobJar.getBytes());
        masterSlaveJobService.saveJob(jarFilePath, packagesToScan);
    } catch (IOException e) {
        throw new NiubiException(e);
    }
    return "forward:/masterSlaveJobSummaries";
}

From source file:org.openmrs.module.visitdocumentsui.ComplexObsSaver.java

public Obs saveOtherDocument(Visit visit, Person person, Encounter encounter, String fileCaption,
        MultipartFile multipartFile, String instructions) throws IOException {
    conceptComplex = context.getConceptComplex(ContentFamily.OTHER);
    prepareComplexObs(visit, person, encounter, fileCaption);

    obs.setComplexData(complexDataHelper.build(instructions, multipartFile.getOriginalFilename(),
            multipartFile.getBytes(), multipartFile.getContentType()).asComplexData());
    obs = context.getObsService().saveObs(obs, getClass().toString());
    return obs;// www.  j  a  v a  2 s.  c  om
}