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:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@Atomic
public AcademicServiceRequestTemplate createAcademicServiceRequestTemplate(
        org.fenixedu.commons.i18n.LocalizedString name, org.fenixedu.commons.i18n.LocalizedString description,
        java.util.Locale language,
        org.fenixedu.academic.domain.serviceRequests.ServiceRequestType serviceRequestType,
        org.fenixedu.academic.domain.degree.DegreeType degreeType, org.fenixedu.academic.domain.Degree degree,
        org.fenixedu.academic.domain.degreeStructure.ProgramConclusion programConclusion,
        MultipartFile documentTemplateFile) throws IOException {

    AcademicServiceRequestTemplate academicServiceRequestTemplate = AcademicServiceRequestTemplate.create(name,
            description, language, serviceRequestType, degreeType, programConclusion, degree);
    DocumentTemplateFile.create(academicServiceRequestTemplate, documentTemplateFile.getOriginalFilename(),
            documentTemplateFile.getBytes());
    return academicServiceRequestTemplate;
}

From source file:gt.dakaik.rest.impl.UserImpl.java

@Override
public ResponseEntity<String> handleFileUpload(Long idUser, MultipartFile file)
        throws EntidadNoEncontradaException {
    User u = repoU.findOne(idUser);/* w w w  .ja v  a2s . c  o m*/
    if (u != null) {
        if (!file.isEmpty()) {
            try {
                File convFile = new File(file.getOriginalFilename());
                convFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(convFile);
                fos.write(file.getBytes());
                fos.close();
                CompressImages cImage = new CompressImages(convFile, "img");
                List<File> files = cImage.getFamilyFixedProcessedFiles();
                System.out.println(files.size() + " files to upload.");

                //************
                String SFTPHOST = "www.colegios.e.gt";
                int SFTPPORT = 1157;
                String SFTPUSER = "colegiose";
                String SFTPPASS = "Dario2015.";
                String SFTPWORKINGDIR = "/home/colegiose/public_html/images/u/";
                String PARENT_PATH = "" + idUser;
                SFTPinJava.saveFileToSftp(files, false, SFTPHOST, SFTPPORT, SFTPUSER, SFTPPASS, SFTPWORKINGDIR,
                        PARENT_PATH);
                //************
                u.setTxtImageURI("http://www.colegios.e.gt/images/u/" + idUser + "/");
                repoU.save(u);
                return new ResponseEntity(u.getTxtImageURI(), HttpStatus.OK);
            } catch (Exception e) {
                e.getMessage();
                throw new EntidadNoEncontradaException();
            }
        } else {
            throw new EntidadNoEncontradaException();
        }
    } else {
        throw new EntidadNoEncontradaException("User");
    }
}

From source file:org.hydroponics.dao.JDBCHydroponicsDaoImpl.java

@Override
public void saveImage(int grow, MultipartFile image) {
    logger.info("save image");

    try {//from w  w  w.  j  av a2s.com
        BufferedImage buffImage = ImageIO.read(image.getInputStream());
        this.jdbcTemplate.update(
                "insert into IMAGE (GROW_ID, timestamp, height, width, mimeType, thumbnail, image) values (?, ?, ?, ?, ?, ?, ?)",
                new Object[] { grow, new Timestamp(System.currentTimeMillis()), buffImage.getHeight(),
                        buffImage.getWidth(), "image/jpeg", getThumbnail(buffImage), image.getBytes() });
    } catch (IOException ex) {
        logger.severe(ex.toString());
    }
}

From source file:org.trpr.platform.batch.impl.spring.web.SynchronizationController.java

/**
 * Receiver methods start/*from   w ww .j a  v  a2s.  com*/
 * These methods receive the job configuration files, dependency files and job loading requests.
 * This method is synchronized as 2 job requests cannot be processed simultaneously
 */
@RequestMapping(value = SynchronizationController.PUSH_URL, method = RequestMethod.POST)
public synchronized String jobReceiver(ModelMap model, @RequestParam String jobName,
        @RequestParam(value = "jobConfig") MultipartFile jobConfig,
        @RequestParam(value = "depFiles[]", required = false) MultipartFile[] depFiles) {
    jobName = jobName.trim();
    LOGGER.info("Push job request received for job: " + jobName);
    //Upload configuration file
    if (this.jobService.contains(jobName)) {
        LOGGER.info("Warning: " + jobName + " already exists. Modifying old file");
    }
    try {
        //Set XML File
        List<String> jobNames = new LinkedList<String>();
        jobNames.add(jobName);
        this.jobConfigService.setJobConfig(jobNames, new ByteArrayResource(jobConfig.getBytes()));
        LOGGER.info("Success in deploying configuration file for: " + jobName);
        model.addAttribute("Message", "success");
    } catch (Exception e) {
        model.addAttribute("Message", "Error while writing the job config file");
        LOGGER.warn("Unable to deploy the job. Please check that you have write permission. Nested exception: "
                + e.getMessage());
        return "sync/Message";
    }
    //Upload dependency Files
    if (depFiles != null && depFiles.length != 0) { //Dep files exist
        for (MultipartFile depFile : depFiles) {
            try {
                //Set dependencies
                LOGGER.info("Request to deploy file: " + jobName + " " + depFile.getOriginalFilename() + " "
                        + depFile.getSize());
                List<String> jobNames = new LinkedList<String>();
                jobNames.add(jobName);
                this.jobConfigService.addJobDependency(jobNames, depFile.getOriginalFilename(),
                        depFile.getBytes());
                LOGGER.info("Success in deploying dependency file for: " + jobName);
                model.addAttribute("Message", "success");
            } catch (Exception e) {
                LOGGER.error("Exception while deploying Dependency file: ", e);
                model.addAttribute("Message",
                        "Unexpected error while deploying dependencyFile: " + depFile.getOriginalFilename());
            }
        }
    }
    LOGGER.info("Deploy request");
    //Deploy request
    try {
        List<String> jobNames = new LinkedList<String>();
        jobNames.add(jobName);
        this.jobConfigService.deployJob(jobNames);
        LOGGER.info("Success in deploying: " + jobName);
        model.addAttribute("Message", "success");
    } catch (Exception e) {
        LOGGER.error("Error while deploying job: " + jobName, e);
        model.addAttribute("Message", "Unexpected error while loading: " + jobName);
    }
    return "sync/Message";
}

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

@RequestMapping(path = "add_new_tree", method = RequestMethod.POST)
public String addNewDocumentForActivityTree(long parent, String name, String description, long documenttype,
        MultipartFile file) {

    Aktivnost aktivnost = activityService.findOne(parent);

    Dokument doc = new Dokument();
    doc.setNaziv(name);//  www.  j a va2 s  .  c o m
    doc.setNapomena(description);
    doc.setDatumKreiranja(new Date());
    doc.setIdAktivnosti(aktivnost);

    Tipdokumenta docType = tipDokumentaService.findOne(documenttype);
    doc.setIdTipaDokumenta(docType);

    String putanja = "n/a";
    String nazivFajla = "n/a";
    String ct = "n/a";
    if (!daLiJePrazan(file)) {

        try {
            byte[] bytes = file.getBytes();
            putanja = "C:" + File.separator + "wamp" + File.separator + "www" + File.separator + "DMS"
                    + File.separator + "files";
            File dir = new File(putanja);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            nazivFajla = file.getOriginalFilename();

            int li = nazivFajla.lastIndexOf("\\");
            //nazivFajla = nazivFajla.substring(li+1, nazivFajla.length());

            File serverFile = new File(dir.getAbsolutePath() + File.separator + nazivFajla); //mozda ovde da bude ime dokumenta umesto naziv fajla
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // return new ModelAndView("error", "error", "Error uploading file! " + " => " + e.getMessage());

        }
    }

    doc.setFajl(putanja + File.separator + nazivFajla);

    dokumentService.save(doc);

    aktivnost.getDokumentList().add(doc);
    activityService.save(aktivnost);

    return "redirect:/processes/usr/overviewusers";
}

From source file:com.oak_yoga_studio.controller.FacultyController.java

@RequestMapping(value = "/updateFacultyProfile", method = RequestMethod.POST)
public String updateUser(@Valid Faculty facultyUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Faculty) session.getAttribute("loggedUser")).getId();
        Faculty faculty = facultyService.getFacultyById(Id);

        faculty.setFirstName(facultyUpdate.getFirstName());
        faculty.setLastName(facultyUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        faculty.setEmail(facultyUpdate.getEmail());

        try {/*from  w  w  w . j  av  a2  s . c  om*/
            System.out.println("Imageeeeeeeeeee - " + file.getBytes());
            if (file.getBytes().length != 0) {
                faculty.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        facultyService.updateFaculty(Id, faculty);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/facultyProfile";
}

From source file:com.pubkit.web.controller.FileUploadController.java

@RequestMapping(value = "/upload_cert", method = RequestMethod.POST)
public @ResponseBody UploadResponse handleFileUpload(@RequestParam("applicationId") String applicationId,
        @RequestParam("fileType") String fileType, @RequestParam("file") MultipartFile multipartFile) {

    LOG.debug("Upload request received for file size:" + multipartFile.getSize());
    validateAccessToken();//from  w w w .  j  a  v a 2 s. c  om

    if (multipartFile != null && !multipartFile.isEmpty()) {
        String fileName = multipartFile.getOriginalFilename();
        try {
            if (TYPE_CERT.equalsIgnoreCase(fileType)) {
                if (!".p12".endsWith(multipartFile.getOriginalFilename())
                        || !".cert".endsWith(multipartFile.getOriginalFilename())) {
                    LOG.debug("Invalid file upload type received");

                    return new UploadResponse("Invalid file type");
                }
            }
            byte[] fileData = multipartFile.getBytes();
            String uploadId = applicationService.saveFile(fileData, fileName, multipartFile.getContentType());
            if (uploadId != null) {
                return new UploadResponse(uploadId, false, null);
            }

            return new UploadResponse("Failed to upload " + fileName);
        } catch (Exception e) {
            LOG.error("Error uploading file", e);
            return new UploadResponse("Failed to upload " + fileName);
        }
    } else {
        LOG.error("Error uploading file");
        return new UploadResponse("Failed to upload");
    }
}

From source file:com.lioland.harmony.web.controller.FileController.java

/**
 * *************************************************
 * URL: /rest/controller/upload upload(): receives files
 *
 * @param request : MultipartHttpServletRequest auto passed
 * @param response : HttpServletResponse auto passed
 * @return LinkedList<FileMeta> as json format
 * **************************************************
 *//*from ww  w  .  j av a2s  .  com*/
@RequestMapping(value = "/file-upload", method = RequestMethod.POST)
public @ResponseBody LinkedList<FileMeta> upload(HttpServletRequest req, HttpServletResponse response) {
    MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
    //1. build an iterator
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    //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());
            File folder = new File("D:\\GitHub\\Harmony\\Harmony\\Web\\src\\main\\webapp\\resources\\files");
            FileUtils.forceMkdir(folder);
            FileCopyUtils.copy(mpf.getBytes(),
                    new FileOutputStream(new File(folder, 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;
}

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

@RequestMapping(path = "add_new/{id}", method = RequestMethod.POST)
public ModelAndView addNewDocumentForActivity(@PathVariable("id") long id, String documentname,
        String documentdescritption, long documenttype, MultipartFile file) {

    Aktivnost aktivnost = activityService.findOne(id);

    Dokument doc = new Dokument();
    doc.setNaziv(documentname);/*from   w w  w . j  ava  2s  .c om*/
    doc.setNapomena(documentdescritption);
    doc.setDatumKreiranja(new Date());
    doc.setIdAktivnosti(aktivnost);

    Tipdokumenta docType = tipDokumentaService.findOne(documenttype);
    doc.setIdTipaDokumenta(docType);

    String putanja = "n/a";
    String nazivFajla = "n/a";
    String ct = "n/a";
    if (!daLiJePrazan(file)) {

        try {
            byte[] bytes = file.getBytes();
            putanja = "C:" + File.separator + "wamp" + File.separator + "www" + File.separator + "DMS"
                    + File.separator + "files";
            File dir = new File(putanja);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            nazivFajla = file.getOriginalFilename();

            int li = nazivFajla.lastIndexOf("\\");
            //nazivFajla = nazivFajla.substring(li+1, nazivFajla.length());

            File serverFile = new File(dir.getAbsolutePath() + File.separator + nazivFajla); //mozda ovde da bude ime dokumenta umesto naziv fajla
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("error", "error", "Error uploading file! " + " => " + e.getMessage());

        }
    }

    doc.setFajl(putanja + File.separator + nazivFajla);

    dokumentService.save(doc);

    aktivnost.getDokumentList().add(doc);
    activityService.save(aktivnost);

    ModelAndView mv = new ModelAndView("processesforusers");

    return mv;
}

From source file:de.document.service.MedikamentService.java

public String transferToFile(MultipartFile file) throws Throwable {
    String filePath2 = Thread.currentThread().getContextClassLoader().getResource("medikament") + "\\"
            + file.getOriginalFilename();
    String filePath = filePath2.substring(6);

    if (!file.isEmpty()) {
        try {//w w w .j  a  v  a2  s.  c  o m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
            return filePath;

        } catch (Exception e) {
            System.out.println("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
        }
    } else {
        System.out
                .println("You failed to upload " + file.getOriginalFilename() + " because the file was empty.");
    }
    return null;
}