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:controller.UploadFileController.java

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String upload(@RequestParam(value = "file") MultipartFile mfile, HttpServletResponse res,
        HttpServletRequest req) {/*from w ww .j a v  a 2 s  .  com*/
    long time = Calendar.getInstance().getTimeInMillis();
    String fileName = "";
    try {
        fileName = time + mfile.getOriginalFilename();
        File f = new File(req.getServletContext().getRealPath("/images") + "/" + fileName);
        if (!f.exists()) {
            f.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(f);
        FileCopyUtils.copy(mfile.getBytes(), out);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "<img src='" + req.getContextPath() + "/images/" + fileName + "'/>";

}

From source file:controllers.FeatureController.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 {/*from  w w w  .  j  ava2  s .com*/
        File newFile = new File("/usr/local/etc/Feature");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            featureService.updateFromXml(newFile);

            ras.addFlashAttribute("error", featureService.getResult().getErrors());

        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml " + StringAdapter.getStackTraceException(e));
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/Feature/show";
}

From source file:pt.ist.fenix.ui.spring.PagesAdminService.java

@Atomic
protected GroupBasedFile addPostFile(MultipartFile attachment, MenuItem menuItem) throws IOException {
    GroupBasedFile f = new GroupBasedFile(attachment.getOriginalFilename(), attachment.getOriginalFilename(),
            attachment.getBytes(), AnyoneGroup.get());
    postForPage(menuItem.getPage()).getPostFiles().putFile(f);
    return f;//from www. j a v  a  2 s. c om
}

From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java

@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/fileGroup/gridFsFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
@Secured({ "ROLE_Result Upload Modify" })
@ResponseBody/*from   www . j av a2s .com*/
public String uploadGridFsFile(@RequestParam("gridFsFile") final MultipartFile gridFsFile,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    String jsonAsStringForIE = null;
    try {
        final GridFSFile savedFile = this.fileGroupService.saveGridFsFile(gridFsFile.getOriginalFilename(),
                gridFsFile.getBytes(), gridFsFile.getContentType());
        jsonAsStringForIE = savedFile.toString();
    } catch (final LocalizedException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    } catch (final IOException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    }

    return jsonAsStringForIE;
}

From source file:controllers.CarOptionValueController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "oldCcoId", required = false) Long oldCcoId,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras)
        throws Exception {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*  www.  ja  v a2 s  .  co m*/
        File newFile = new File("/usr/local/etc/covs");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carOptionValueService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carOptionValueService.getResult().getErrors());
        } catch (Exception e) {
            List<String> erList = new ArrayList();
            erList.addAll(carOptionValueService.getResult().getErrors());
            erList.add(e.getMessage());
            ras.addFlashAttribute("error",
                    "updateFromXml: " + /*StringAdapter.getStackTraceException(e)*/erList);

        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("ccoId", oldCcoId);
    return "redirect:/CarOptionValue/show";
}

From source file:cs425.yogastudio.controller.SignupController.java

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(String firstname, String lastname, String email, String username, String password,
        String state, String zip, String street, String city, Model model, HttpSession session,
        @RequestParam("file") MultipartFile file) {

    if (checkUsername(username)) {
        session.setAttribute("nonUniqueMessage", null);

        Customer newCustomer = new Customer(firstname, lastname, email, username, password);
        Address newAddress = new Address(state, zip, street, city);
        //         ShoppingCart shoppingCart = new ShoppingCart(newCustomer);

        if (!file.isEmpty()) {
            try {
                newCustomer.setProductImage(file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();//  www  .j a  v  a2 s  .  c  om
            }
        }

        newCustomer.addAddress(newAddress);
        customerService.addCustomer(newCustomer);
        //model.addAttribute("newcustomer", newCustomer);
        session.setAttribute("added", newCustomer.getFirstName());
        return "redirect:/signUpSuccess";
    } else {
        session.setAttribute("nonUniqueMessage", "username already exists, try another one");
        return "redirect:/customerSignup";
    }

}

From source file:com.devnexus.ting.web.controller.admin.AdminScheduleController.java

private List<ScheduleItem> processScheduleCsv(Event event, MultipartFile scheduleCsv,
        BindingResult bindingResult) {/*w ww. j  a v  a  2s .  com*/
    List<ScheduleItem> scheduleItems = new ArrayList<>();
    byte[] scheduleCsvData = null;

    try {
        scheduleCsvData = scheduleCsv.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Schedule CSV File.", e);
        bindingResult.addError(
                new FieldError("uploadScheduleForm", "scheduleFile", "Error processing Schedule CSV File."));
        return null;
    }

    if (scheduleCsvData != null && scheduleCsv.getSize() > 0) {

        final ByteArrayInputStream bais = new ByteArrayInputStream(scheduleCsvData);

        ICsvBeanReader beanReader = null;
        try {
            final Reader reader = new InputStreamReader(bais);
            beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);

            // the header elements are used to map the values to the bean (names must match)
            final String[] header = beanReader.getHeader(true);
            final CellProcessor[] processors = CsvScheduleItemBean.getImportProcessors();

            CsvScheduleItemBean scheduleItemBean;
            while ((scheduleItemBean = beanReader.read(CsvScheduleItemBean.class, header,
                    processors)) != null) {
                final ScheduleItem scheduleItem;

                if (scheduleItemBean.getId() != null) {
                    scheduleItem = businessService.getScheduleItem(scheduleItemBean.getId());
                    if (scheduleItem == null) {
                        LOGGER.error(String.format("Schedule Item with Id '%s' does not exist.",
                                scheduleItemBean.getId()));
                        bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                                String.format("Schedule Item with Id '%s' does not exist.",
                                        scheduleItemBean.getId())));
                        continue;
                    }
                } else {
                    scheduleItem = new ScheduleItem();
                }

                if (scheduleItemBean.getEventId() != null) {
                    if (event.getId().equals(scheduleItemBean.getEventId())) {
                        scheduleItem.setEvent(event);
                    } else {
                        throw new IllegalArgumentException("Event ID did not match.");
                    }
                } else {
                    scheduleItem.setEvent(event);
                }

                scheduleItem.setFromTime(scheduleItemBean.getFromTime());
                scheduleItem.setToTime(scheduleItemBean.getToTime());
                scheduleItem.setScheduleItemType(scheduleItemBean.getType());
                scheduleItem.setTitle(scheduleItemBean.getTitle());

                if (scheduleItemBean.getPresentationId() != null) {
                    final Presentation presentation = businessService
                            .getPresentation(scheduleItemBean.getPresentationId());
                    scheduleItem.setPresentation(presentation);
                } else {
                    scheduleItem.setPresentation(null);
                }

                if (scheduleItemBean.getRoomId() != null) {
                    final Room room = businessService.getRoom(scheduleItemBean.getRoomId());
                    scheduleItem.setRoom(room);
                } else {
                    scheduleItem.setRoom(null);
                }

                scheduleItems.add(scheduleItem);

            }
        } catch (IOException e) {
            LOGGER.error("Error processing CSV File.", e);
            bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                    "Error processing Schedule CSV File."));
            return null;
        } finally {
            if (beanReader != null) {
                try {
                    beanReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    return scheduleItems;
}

From source file:pt.ist.fenix.ui.spring.PagesAdminService.java

@Atomic(mode = Atomic.TxMode.WRITE)
protected GroupBasedFile addAttachment(String name, MultipartFile attachment, MenuItem menuItem)
        throws IOException {
    Post post = postForPage(menuItem.getPage());
    GroupBasedFile file = new GroupBasedFile(name, attachment.getOriginalFilename(), attachment.getBytes(),
            AnyoneGroup.get());/*from   w ww . j  av  a  2  s . c  o  m*/
    post.getAttachments().putFile(file, 0);
    return file;
}

From source file:controllers.PropertyController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "propId", required = true) Long propId,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras)
        throws Exception {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//from   w w  w  .  j  av  a2  s  . c  o m
        File newFile = new File("/usr/local/etc/Properties");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            propertyNameService.updateFromXml(newFile);
            ras.addFlashAttribute("error", propertyNameService.getResult().getErrors());
        } catch (Exception e) {
            //ras.addFlashAttribute("error", "updateFromXml"+e.getMessage());
            throw new Exception(StringAdapter.getStackTraceException(e));
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("propId", propId);
    return "redirect:/PropertyName/show";
}