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.spee.sbweb.controller.UploadController.java

@RequestMapping(value = "/file", method = { RequestMethod.POST,
        RequestMethod.OPTIONS }, produces = "application/json")
public @ResponseBody AlvisModel upload(HttpServletRequest request, HttpServletResponse response,
        @RequestPart("file") MultipartFile file, @RequestBody String x) throws Exception {
    String seq = new String(file.getBytes(), "UTF-8");
    return validate(request, seq);
}

From source file:com.linksinnovation.elearning.controller.api.UserController.java

@RequestMapping(value = "/user/avatar", method = RequestMethod.POST)
public String avatarUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        @AuthenticationPrincipal String user) throws Exception {
    if (!file.isEmpty()) {
        String fileName = user + "-" + name;

        byte[] bytes = file.getBytes();
        try (BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File("/mnt/data/images/avatar/" + fileName)))) {
            stream.write(bytes);/*  w  w  w  .  j a  va 2  s .  c  o m*/
        }

        UserDetails userDetails = userDetailsRepository.findOne(user.toUpperCase());
        userDetails.setAvatar(fileName);
        userDetailsRepository.save(userDetails);

        return fileName;
    } else {
        throw new Exception("You failed to upload because the file was empty.");
    }
}

From source file:org.jasig.portlet.test.mvc.tests.FileUploadController.java

@ActionMapping("fileUploadAction")
public void simpleFileUpload(PortletSession portletSession, @RequestParam("file") MultipartFile f)
        throws IOException {
    final Map<String, ? extends Object> fileInfo = ImmutableMap.of("size", f.getSize(), "originalFilename",
            f.getOriginalFilename(), "name", f.getName(), "contentType", f.getContentType(), "byteCount",
            f.getBytes().length);

    portletSession.setAttribute(UPLOADED_FILE_INFO, fileInfo);
}

From source file:org.khmeracademy.btb.auc.pojo.service.impl.UploadImage_serviceimpl.java

@Override
public Image upload(int pro_id, List<MultipartFile> files) {
    Image uploadImage = new Image();
    if (files.isEmpty()) {

    } else {//from  w  ww  . java  2 s. com

        //            if(folder=="" || folder==null)
        //                folder = "default";
        String UPLOAD_PATH = "/opt/project/default";
        String THUMBNAIL_PATH = "/opt/project/thumnail/";

        java.io.File path = new java.io.File(UPLOAD_PATH);
        java.io.File thum_path = new java.io.File(THUMBNAIL_PATH);
        if (!path.exists())
            path.mkdirs();
        if (!thum_path.exists()) {
            thum_path.mkdirs();
        }

        List<String> names = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
            try {
                byte[] bytes = file.getBytes();
                Files.copy(file.getInputStream(), Paths.get(UPLOAD_PATH, fileName)); //copy path name to server
                try {
                    //TODO: USING THUMBNAILS TO RESIZE THE IMAGE

                    Thumbnails.of(UPLOAD_PATH + "/" + fileName).forceSize(640, 640).toFiles(thum_path,
                            Rename.NO_CHANGE);
                } catch (Exception ex) {
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(new File(THUMBNAIL_PATH + fileName)));
                    stream.write(bytes);
                    stream.close();
                }
                names.add(fileName); // add file name
                imRepo.upload(pro_id, fileName); // upload path to database
            } catch (Exception e) {

            }
        }
        uploadImage.setProjectPath("/resources/");
        uploadImage.setServerPath(UPLOAD_PATH);
        uploadImage.setNames(names);
        uploadImage.setMessage("File has been uploaded successfully!!!");
    }
    return uploadImage;
}

From source file:org.tonguetied.web.ImportController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("beginning import");
    // cast the bean
    ImportBean bean = (ImportBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFileUploadBean().getFile();
    if (file != null && !file.isEmpty()) {
        bean.getParameters().setFileName(FilenameUtils.getBaseName(file.getOriginalFilename()));
        bean.getParameters().setData(file.getBytes());
        dataService.importData(bean.getParameters());
    } else {/*from   w w  w.  j  a  v a  2s.  c  o m*/
        // hmm, that's strange, the user did not upload anything
    }

    return new ModelAndView(getSuccessView());
}

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

@RequestMapping(value = "/savedpage", method = RequestMethod.POST)
public ModelAndView savedpage(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam("cover") MultipartFile cover, @RequestParam("file") MultipartFile[] files)
        throws InterruptedException {
    ModelAndView model = new ModelAndView("okpageadmin");

    DeepeningPage dp = new DeepeningPage();
    dp.setName(params.get("name"));
    System.out.println(params.get("name"));

    int i = 1;/*  w  ww .  ja v a 2  s.  c  o m*/
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

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

        i = i + 1;
    }
    dp.setCategories(categories);

    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

    //componente cover
    if (!cover.isEmpty()) {
        CoverImgComponent coverimg = new CoverImgComponent();
        coverimg.setLink("cover.jpg");
        listComponent.add(coverimg);
    }
    //componente galleria immagini
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    if (files.length > 0) {
        ImgGalleryComponent img_gallery = new ImgGalleryComponent();

        i = 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("credit" + (i + 1))) {
                img.setCredit(params.get("credit" + (i + 1)));
            }

            i = i + 1;
            links.add(img);
        }
        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);
    }
    dp.setComponents(listComponent);

    pm.saveDeepeningPage(dp);

    DeepeningPage poi2 = pm.findDeepeningPageByName(dp.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();

        } catch (Exception e) {

            model.addObject("mess", "ERRORE!");
            return model;
        }
    }
    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) {

    }
    model.addObject("mess", "PAGINA INSERITA CORRETTAMENTE!");
    return model;
}

From source file:app.springapp.FileUploadController.java

public BufferedImage convert(MultipartFile file) {
    BufferedImage im = null;//ww  w  . j a v a2s . c  om
    File convFile = new File(file.getOriginalFilename());

    try {
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        im = ImageIO.read(convFile);
    } catch (IOException e) {

    }

    return im;

}

From source file:controllers.ParseBaseController.java

@RequestMapping("/addFile")
public String addFile(Map<String, Object> model, @RequestParam("newFile") MultipartFile file)
        throws IOException {
    File newFile = new File("/usr/local/etc/qutoCatalog.sql");
    //++?   ???  
    if (!newFile.exists()) {
        FileUtils.writeByteArrayToFile(newFile, file.getBytes());
    } else {// w w  w  .j  a  v a 2  s.c o m
        newFile.delete();
        FileUtils.writeByteArrayToFile(newFile, file.getBytes());
    }
    return "redirect:/ParseBaseController/show";
}

From source file:org.openxdata.server.servlet.MultimediaServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String formId = request.getParameter("formId");
    String xpath = request.getParameter("xpath");

    CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
    if (multipartResover.isMultipart(request)) {
        MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
        MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
        if (uploadedFile != null && !uploadedFile.isEmpty()) {
            byte[] postData = uploadedFile.getBytes();
            response.getOutputStream().print(new String(Base64.encodeBase64(postData)));

            setSessionData(request, formId, KEY_MULTIMEDIA_POST_CONTENT_TYPE + getFieldKey(formId, xpath),
                    uploadedFile.getContentType());
            setSessionData(request, formId, KEY_MULTIMEDIA_POST_DATA + getFieldKey(formId, xpath), postData);
        }/*  w  w w .  j a va 2s .co  m*/
    }
}

From source file:eu.domibus.web.controller.AdminGUIController.java

/**
 * Upload single file using Spring Controller
 */// www.  j a v  a2  s .  com
@ResponseBody
@RequestMapping(value = "/home/updatepmode", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            this.pModeProvider.updatePModes(bytes);
            return "You successfully uploaded the PMode file.";
        } catch (Exception e) {
            AdminGUIController.LOG.error("", e);
            return "You failed to upload the PMode file. => " + e.getMessage();
        }
    } else {
        return "You failed to upload the PMode file. The file was empty.";
    }
}