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:dijalmasilva.controllers.ControladorUser.java

@RequestMapping(value = { "/update" })
public String atualizarPerfil(UsuarioForm u, HttpServletRequest req, MultipartFile foto) throws IOException {
    Usuario usuario = this.convertToUsuario(u, null);
    Usuario user = (Usuario) req.getSession().getAttribute("user");
    atualizaUsuario(user, usuario);/*w  w w  .  j av a  2 s . c o  m*/
    if (foto.getSize() != 0) {
        user.setFoto(foto.getBytes());
    }
    user = serviceUser.atualizarPerfil(user);
    if (user == null) {
        req.setAttribute("result", "No foi possvel atualizar seu perfil, verifique se todos os campos foram"
                + " preenchidos corretamente!");
    } else {
        req.setAttribute("result", "Perfil atualizado com sucesso.");
    }

    return "redirect:/user/home";
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceImpl.java

/**
 * Creates new DataFile under specified experiment.
 *
 * @param experimentId experiment identifier
 * @param description  data file description
 * @param file         data file multipart
 * @return identifier of created record//from  w  w w  . jav  a 2  s.c om
 * @throws IOException error while creating record
 */
@Override
@Transactional
public int create(int experimentId, String description, MultipartFile file) throws IOException {
    DataFile datafile = new DataFile();
    datafile.setExperiment(experimentDao.getExperimentForDetail(experimentId));
    datafile.setDescription(description);
    datafile.setFilename(file.getOriginalFilename().replace(" ", "_"));
    datafile.setFileContent(Hibernate.createBlob(file.getBytes()));
    datafile.setMimetype(
            file.getContentType() != null ? file.getContentType().toLowerCase() : "application/octet-stream");

    //DB column size restriction
    if (datafile.getMimetype().length() > 40) {
        datafile.setMimetype("application/octet-stream");
    }
    return dataFileDao.create(datafile);
}

From source file:org.openmrs.module.bannerprototype.web.controller.bannerprototypeManageController.java

@RequestMapping(value = "/module/bannerprototype/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) throws IOException {

    String path = new ClassPathResource("taggers/").getURL().getPath();
    if (!file.isEmpty()) {
        try {// w  ww .  ja va  2  s . c  o  m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + name)));
            stream.write(bytes);
            stream.close();

            return "You successfully uploaded " + name + "!\n<a href=manage.form>back</a>";
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return "ERROR:  Please name your file";

        } catch (Exception e) {
            e.printStackTrace();
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:org.fenixedu.ulisboa.integration.sas.ui.spring.controller.manageScholarshipReportRequests.ScholarshipReportRequestController.java

@RequestMapping(value = "/createscholarshipreportrequeststep2", method = RequestMethod.POST)
public String createscholarshipreportrequeststep2(
        @RequestParam(value = "executionyear", required = false) ExecutionYear executionYear,
        @RequestParam(value = "firstyearofcycle", required = false) boolean firstYearOfCycle,
        @RequestParam(value = "contractualisation", required = false) boolean contractualisation,
        @RequestParam(value = "file") MultipartFile file, Model model, RedirectAttributes redirectAttributes) {

    try {/*w w w . j ava 2 s  .  co m*/

        ScholarshipReportRequest scholarshipReportRequest = createScholarshipReportRequest(executionYear,
                firstYearOfCycle, contractualisation, file.getOriginalFilename(), file.getBytes());

        model.addAttribute("scholarshipReportRequest", scholarshipReportRequest);
        return redirect("/integration/sas/managescholarshipreportrequests/scholarshipreportrequest/", model,
                redirectAttributes);
    } catch (DomainException de) {
        addErrorMessage(" Error creating due to " + de.getLocalizedMessage(), model);
        return createscholarshipreportrequeststep2(model, executionYear, firstYearOfCycle, contractualisation);
    } catch (IOException e) {
        //TODO what to do here?
        addErrorMessage(" Error reading submitted file", model);
        return createscholarshipreportrequeststep2(model, executionYear, firstYearOfCycle, contractualisation);
    }
}

From source file:com.sivalabs.jcart.admin.web.controllers.ProductController.java

protected void saveProductImageToDisk(ProductForm productForm) {
    MultipartFile file = productForm.getImage();
    if (nonNull(file) && !file.isEmpty()) {
        String name = new StringBuilder(IMAGES_DIR).append(productForm.getId()).append(".jpg").toString();
        try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)))) {
            byte[] bytes = file.getBytes();
            stream.write(bytes);//from  w w w . j a v  a2s. c  o m
        } catch (IOException e) {
            throw new JCartException(e);
        }
    }
}

From source file:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = { "/system/do/uploadfile", "/system/do/uploadfile/" }, method = RequestMethod.POST)
public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {//from   ww w  .  j  a va2s  . c  om
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return "";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

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

/**
 * Add a new script to a project//  w  ww  . j  av  a  2 s.  com
 * @param projectId   ID of the project
 * @param script   Script to add (from HTML form binding)
 * @param file   Uploaded file of the script (JMX or other)
 * @return Redirection to the script detail page
 */
@RequestMapping(value = "/project/{projectId}/script/new", method = RequestMethod.POST)
public String addScript(@PathVariable("projectId") Long projectId, @ModelAttribute("script") Script script,
        @RequestParam("jmxFile") MultipartFile file) {
    String scriptContent = null;

    // Get the script File
    try {
        scriptContent = new String(file.getBytes());
    } catch (IOException e) {
    }
    Script newScript = scriptService.addScript(script.getProject(), script.getSamplerUID(), script.getLabel(),
            script.getDescription(), scriptContent);
    return "redirect:/project/" + projectId + "/script/" + newScript.getId() + "/detail";
}

From source file:com.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }/*from  w w w .j a  v  a2s  . c om*/
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {

        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:controllers.FreeOptionController.java

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

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

/**
 * Add a version to a script//from  ww  w  .ja va  2s  .  com
 * @param projectId   ID of the project
 * @param scriptId   ID of the script
 * @param scriptVersion   Script version to add (from HTML form binding)
 * @param file Uploaded file of the script (JMX or other)
 * @return Redirection to the script detail page
 */
@RequestMapping(value = "/project/{projectId}/script/{scriptId}/version/new", method = RequestMethod.POST)
public String addScriptVersion(@PathVariable("projectId") Long projectId,
        @PathVariable("scriptId") Long scriptId, @ModelAttribute("scriptVersion") ScriptVersion scriptVersion,
        @RequestParam("scriptFile") MultipartFile file) {
    String scriptContent = null;

    // Get the script File
    try {
        scriptContent = new String(file.getBytes());
    } catch (IOException e) {
    }
    ScriptVersion newScriptVersion = scriptService.addScriptVersion(scriptRepository.findOne(scriptId),
            scriptVersion.getDescription(), scriptContent);
    return "redirect:/project/" + projectId + "/script/" + scriptId + "/detail#" + newScriptVersion.getId();
}