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:de.appsolve.padelcampus.admin.controller.general.AdminGeneralDesignController.java

@RequestMapping(method = POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ModelAndView postIndex(HttpServletRequest request,
        @RequestParam("backgroundImage") MultipartFile backgroundImage,
        @RequestParam(value = "backgroundImageRepeat", required = false, defaultValue = "false") Boolean backgroundImageRepeat,
        @RequestParam(value = "backgroundSizeCover", required = false, defaultValue = "false") Boolean backgroundSizeCover,
        @RequestParam(value = "loaderOpacity", required = false, defaultValue = "false") Boolean loaderOpacity,
        @RequestParam("companyLogo") MultipartFile companyLogo,
        @RequestParam("touchIcon") MultipartFile touchIcon) throws Exception {
    List<CssAttribute> atts = htmlResourceUtil.getCssAttributes();
    for (CssAttribute att : atts) {
        switch (att.getName()) {
        case "backgroundImage":
            if (!backgroundImage.isEmpty()) {
                StringBuilder sb = new StringBuilder("url(data:");
                sb.append(backgroundImage.getContentType());
                sb.append(";base64,");
                sb.append(Base64.encodeBase64String(backgroundImage.getBytes()));
                sb.append(")");
                att.setCssValue(sb.toString());
            }//from   w  w  w. j a va2 s . c  om
            break;
        case "backgroundRepeat":
            if (backgroundImageRepeat) {
                att.setCssValue("repeat");
            } else {
                att.setCssValue("no-repeat");
            }
            break;
        case "backgroundSize":
            if (backgroundSizeCover) {
                att.setCssValue("cover");
            } else {
                att.setCssValue("inherit");
            }
            break;
        case "loaderOpacity":
            if (loaderOpacity) {
                att.setCssValue("@loaderOpacity: 1");
            } else {
                att.setCssValue("@loaderOpacity: 0");
            }
            break;
        default:
            att.setCssValue(request.getParameter(att.getName() + ""));
        }
        cssAttributeDAO.saveOrUpdate(att);
    }
    Customer customer = (Customer) sessionUtil.getCustomer(request);
    if (!companyLogo.isEmpty()) {

        //delete old picture from FS if it exists. will be removed from DB automatically due to orphanRemoval=true
        deleteImage(customer.getCompanyLogo());
        customer.setCompanyLogo(null);
        customerDAO.saveOrUpdate(customer);

        Image newImage = imageUtil.saveImage(companyLogo.getContentType(), companyLogo.getBytes(),
                ImageCategory.companyIcon);
        customer.setCompanyLogo(newImage);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }
    if (!touchIcon.isEmpty()) {
        //delete old picture from FS
        deleteImage(customer.getTouchIcon());
        customer.setTouchIcon(null);
        customerDAO.saveOrUpdate(customer);

        Image image = imageUtil.saveImage(touchIcon.getContentType(), touchIcon.getBytes(),
                Constants.TOUCH_ICON_WIDTH, Constants.TOUCH_ICON_HEIGHT, ImageCategory.touchIcon);
        customer.setTouchIcon(image);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }

    htmlResourceUtil.updateCss(request.getServletContext(), customer);
    return getIndexView(atts);
}

From source file:com.abixen.platform.core.application.service.LayoutManagementService.java

@PreAuthorize("hasPermission(#id, '" + AclClassName.Values.LAYOUT + "', '" + PermissionName.Values.LAYOUT_EDIT
        + "')")//from  www  .  j av a  2  s  .  c  o m
public LayoutDto changeLayoutIcon(final Long id, final MultipartFile iconFile) throws IOException {
    log.debug("changeLayoutIcon() - id: {}, iconFile: {}", id, iconFile);

    final Layout layout = layoutService.find(id);
    //FIXME - rename to thumbnail
    final File currentThumbnailFile = new File(
            platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/"
                    + layout.getIconFileName());

    if (currentThumbnailFile.exists()) {
        if (!currentThumbnailFile.delete()) {
            throw new FileExistsException();
        }
    }

    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    final String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime())
            .replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
    final File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/layout-miniature/" + newIconFileName);

    final FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();

    layout.changeIconFileName(newIconFileName);
    final Layout updatedLayout = layoutService.update(layout);

    return layoutToLayoutDtoConverter.convert(updatedLayout);
}

From source file:Controller.MessageController.java

@RequestMapping(value = "/Image/Booking/upload", method = RequestMethod.POST)
public @ResponseBody String uploadImageForBooking(@RequestParam("uploadImage") MultipartFile uploadImage,
        HttpSession session, @RequestParam("bookingID") String bookingID) {
    try {//from  w w  w  .  j  a  va  2 s  .co  m
        String path = System.getProperty("catalina.base");
        File folderPackage = new File(path + "/webapps/Chat/Upload/" + bookingID);
        if (!folderPackage.exists()) {
            folderPackage.mkdirs();
        }
        String name = uploadImage.getOriginalFilename();
        FileCopyUtils.copy(uploadImage.getBytes(), new FileOutputStream(new File(folderPackage, name)));
        Gson gson = new Gson();
        if (session != null) {

            AccountSession account = (AccountSession) session.getAttribute("account");
            if (providerService.isProvider(account)) {
                gson.toJson(messageService.sendBookingMessage(
                        "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\"}",
                        "provider", account.getId(), bookingID));
                int tripperID;
                try {
                    tripperID = messageService.getTripperIDByBookingCode(bookingID);
                } catch (Exception e) {
                    tripperID = 0;
                }
                template.convertAndSend("/topic/getUnReadBookingForTripper/" + tripperID,
                        new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
            } else if (tripperService.isUser(account)) {
                gson.toJson(messageService.sendBookingMessage(
                        "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\"}",
                        "tripper", account.getId(), bookingID));
                int providerID;
                try {
                    providerID = messageService.getProviderIDByBookingCode(bookingID);
                } catch (Exception e) {
                    providerID = 0;
                }
                template.convertAndSend("/topic/getUnReadBookingForProvider/" + providerID,
                        new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
            }
            template.convertAndSend("/topic/package/" + bookingID,
                    new Greeting("{\"Type\":\"booking\",\"conversationID\":\"" + bookingID + "\"}"));
        }
        return "/Chat/Upload/" + bookingID + "/" + name;
    } catch (Exception e) {
        String content = "Function: MessageController - uploadImageForBooking\n" + "***Input***\n"
                + "bookingID: " + bookingID + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n"
                + "**********";
        errorService.logBugWithAccount(content, session, e);
        return "{\"result\": \"error\"}";
    }
}

From source file:com.glaf.core.web.springmvc.MxUploadController.java

@RequestMapping("/uploadNow")
public ModelAndView upload(HttpServletRequest request, ModelMap modelMap) {
    LoginContext loginContext = RequestUtils.getLoginContext(request);

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    String type = req.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }//w  w w .j  av  a 2s. co  m

    String serviceKey = req.getParameter("serviceKey");
    if (StringUtils.isEmpty(serviceKey)) {
        modelMap.put("error_message", "????serviceKey?");
        return new ModelAndView("/error");
    }

    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    logger.debug("paramMap:" + paramMap);
    String businessKey = req.getParameter("businessKey");
    String objectId = req.getParameter("objectId");
    String objectValue = req.getParameter("objectValue");
    int status = ParamUtils.getInt(paramMap, "status");
    List<DataFile> dataFiles = new java.util.ArrayList<DataFile>();
    try {
        semaphore.acquire();

        if (StringUtils.isNotEmpty(businessKey)) {
            List<DataFile> rows = blobService.getBlobList(businessKey);
            if (rows != null && rows.size() > 0) {
                dataFiles.addAll(rows);
            }
        }

        paramMap.remove("businessKey");
        paramMap.put("createBy", loginContext.getActorId());
        paramMap.put("serviceKey", serviceKey);
        paramMap.put("status", status);
        BlobItemQuery query = new BlobItemQuery();
        Tools.populate(query, paramMap);

        query.createBy(loginContext.getActorId());
        query.serviceKey(serviceKey);
        query.status(status);
        List<DataFile> rows = blobService.getBlobList(query);
        if (rows != null && rows.size() > 0) {
            Iterator<DataFile> iterator = rows.iterator();
            while (iterator.hasNext()) {
                DataFile dataFile = iterator.next();
                if (!dataFiles.contains(dataFile)) {
                    dataFiles.add(dataFile);
                }
            }
        }

        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                String filename = mFile.getOriginalFilename();
                logger.debug("upload file:" + filename);
                String fileId = UUID32.getUUID();
                if (filename.indexOf("/") != -1) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
                } else if (filename.indexOf("\\") != -1) {
                    filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
                }
                BlobItem dataFile = new BlobItemEntity();
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setFileId(fileId);
                dataFile.setData(mFile.getBytes());
                dataFile.setFilename(filename);
                dataFile.setName(mFile.getName());
                dataFile.setContentType(mFile.getContentType());
                dataFile.setSize((int) mFile.getSize());
                dataFile.setType(type);
                dataFile.setStatus(status);
                dataFile.setObjectId(objectId);
                dataFile.setObjectValue(objectValue);
                dataFile.setServiceKey(serviceKey);
                blobService.insertBlob(dataFile);
                dataFile.setData(null);
                dataFiles.add(dataFile);
            }
        }

        if (dataFiles.size() > 0) {
            modelMap.put("dataFiles", dataFiles);
        }

    } catch (Exception ex) {
        logger.debug(ex);
        return new ModelAndView("/error");
    } finally {
        semaphore.release();
    }

    return this.showUpload(request, modelMap);
}

From source file:kr.co.exsoft.external.controller.ExternalPublicController.java

@RequestMapping(value = "/restful.singleUpload", method = RequestMethod.POST)
@ResponseBody/*  w  ww  .j a  v a  2  s. c  o  m*/
public String singleFileUploadTest(@RequestParam("uploadBox") MultipartFile file) { // <input type="file" name="uploadBox">
    String name = "File not found";
    if (!file.isEmpty()) {
        try {
            name = file.getName();
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(name + "-uploaded")));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } 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:com.cisco.ca.cstg.pdi.controllers.license.LicenseController.java

@RequestMapping(value = "/licenseUpload.html", method = RequestMethod.POST)
public ModelAndView licenseUpload(@RequestParam("upload_license") MultipartFile file) {
    ModelAndView modelAndView = null;/*from  w  w w  .ja  va  2 s  . c  o m*/

    if (file == null) {
        modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE, "The file is null.");
    } else {

        String fileName = file.getOriginalFilename();
        LOGGER.info("File Name is " + fileName);
        if ((fileName == null) || (fileName.trim().length() <= 0)) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "No File Uploaded. Please select a file and upload.");
        } else if (!fileName.toLowerCase().matches(".*\\.lic$|.*\\.txt$")) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "The uploaded file is not an text file ending with .lic or .txt extension.");
        } else if (file.isEmpty()) {
            modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                    "The uploaded file does not contain any data.");
        } else {

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

                String key = new String(fileContent, Charset.defaultCharset());

                licenseKeyService.setKey(key);

                try {
                    Util.writeFile(PdiConfig.getProperty(Constants.PDI_HOME), fileContent,
                            Constants.LICENSE_FILENAME);
                    LicenseFileValidator.getInstance().resetFileStatus();
                } catch (FileNotFoundException fnfe) {
                    LOGGER.error("Could not locate file.", fnfe);
                } catch (IOException e) {
                    LOGGER.error("Error writing file.", e);
                }

                modelAndView = new ModelAndView("redirect: listProjects.html");

            } catch (LicenseParsingException lpe) {
                LOGGER.error("Exception: ", lpe);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        lpe.getMessage() + ".");
            } catch (IOException ioe) {
                LOGGER.error("Exception: ", ioe);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        "Error reading uploaded file. Please try upload again.");
            } catch (Exception exception) {
                LOGGER.error("Exception: ", exception);
                modelAndView = new ModelAndView(RESPONSE_LICENSE_UPLOAD, KEY_ERROR_MESSAGE,
                        "Unknown error occurred. Please try upload again.");
            }
        }
    }
    return modelAndView;
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImpl.java

/**
 * Process a file uploaded on the add step event.
 * @param request {@link MultipartHttpServletRequest}
 * @param archive {@link ArchiveDTO}/* w  ww .j av  a 2  s . c om*/
 */
private void eventIdaddstepFileUpload(final MultipartHttpServletRequest request, final ArchiveDTO archive) {
    Iterator<String> itr = request.getFileNames();
    String filename = itr.next();
    MultipartFile mpf = request.getFile(filename);

    try {

        for (WorkflowOutputGenerator gen : this.context.getBeansOfType(WorkflowOutputGenerator.class)
                .values()) {

            String ext = gen.getNewWorkflowOutputDocument().getInputDocumentType().getExtension();

            if (mpf.getOriginalFilename().endsWith(ext)) {
                gen.generate(archive, mpf.getOriginalFilename(), mpf.getBytes());
            }
        }
        // TODO handle no output generator found.
    } catch (IOException e) {
        // TODO display error message
        LOG.log(Level.WARNING, e.getMessage(), e);
    }
}

From source file:Controller.MessageController.java

@RequestMapping(value = "/File/Booking/upload", method = RequestMethod.POST)
public @ResponseBody String uploadFileForBooking(@RequestParam("uploadFile") MultipartFile uploadFile,
        HttpSession session, @RequestParam("bookingID") String bookingID) {
    try {/*ww  w . j  a  v a2  s  . c  o  m*/
        String path = System.getProperty("catalina.base");
        File folderPackage = new File(path + "/webapps/Chat/Upload/" + bookingID);
        if (!folderPackage.exists()) {
            folderPackage.mkdirs();
        }
        String name = uploadFile.getOriginalFilename();
        FileCopyUtils.copy(uploadFile.getBytes(), new FileOutputStream(new File(folderPackage, name)));
        Gson gson = new Gson();
        if (session != null) {
            if (FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("png")
                    || FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("jpg")
                    || FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("gif")) {
                AccountSession account = (AccountSession) session.getAttribute("account");
                if (providerService.isProvider(account)) {
                    gson.toJson(messageService.sendBookingMessage(
                            "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name
                                    + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}",
                            "provider", account.getId(), bookingID));
                    int tripperID;
                    try {
                        tripperID = messageService.getTripperIDByBookingCode(bookingID);
                    } catch (Exception e) {
                        tripperID = 0;
                    }
                    template.convertAndSend("/topic/getUnReadBookingForTripper/" + tripperID, new Greeting(
                            "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
                } else if (tripperService.isUser(account)) {
                    gson.toJson(messageService.sendBookingMessage(
                            "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name
                                    + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}",
                            "tripper", account.getId(), bookingID));
                    int providerID;
                    try {
                        providerID = messageService.getProviderIDByBookingCode(bookingID);
                    } catch (Exception e) {
                        providerID = 0;
                    }
                    template.convertAndSend("/topic/getUnReadBookingForProvider/" + providerID, new Greeting(
                            "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
                }
                template.convertAndSend("/topic/package/" + bookingID,
                        new Greeting("{\"Type\":\"booking\",\"conversationID\":\"" + bookingID + "\"}"));
            } else {
                AccountSession account = (AccountSession) session.getAttribute("account");
                if (providerService.isProvider(account)) {
                    gson.toJson(messageService.sendBookingMessage(
                            "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name
                                    + "\",\"type\":\"file\",\"filename\":\"" + name + "\"}",
                            "provider", account.getId(), bookingID));
                    int tripperID;
                    try {
                        tripperID = messageService.getTripperIDByBookingCode(bookingID);
                    } catch (Exception e) {
                        tripperID = 0;
                    }
                    template.convertAndSend("/topic/getUnReadBookingForTripper/" + tripperID, new Greeting(
                            "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
                } else if (tripperService.isUser(account)) {
                    gson.toJson(messageService.sendBookingMessage(
                            "{\"content\":\"" + "/Chat/Upload/" + bookingID + "/" + name
                                    + "\",\"type\":\"file\",\"filename\":\"" + name + "\"}",
                            "tripper", account.getId(), bookingID));
                    int providerID;
                    try {
                        providerID = messageService.getProviderIDByBookingCode(bookingID);
                    } catch (Exception e) {
                        providerID = 0;
                    }
                    template.convertAndSend("/topic/getUnReadBookingForProvider/" + providerID, new Greeting(
                            "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}"));
                }
                template.convertAndSend("/topic/package/" + bookingID,
                        new Greeting("{\"Type\":\"booking\",\"conversationID\":\"" + bookingID + "\"}"));
            }
        }
        return "/Chat/Upload/" + bookingID + "/" + name;
    } catch (Exception e) {
        String content = "Function: MessageController - uploadFileForBooking\n" + "***Input***\n"
                + "bookingID: " + bookingID + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n"
                + "**********";
        errorService.logBugWithAccount(content, session, e);
        return "{\"result\": \"error\"}";
    }
}

From source file:com.denimgroup.threadfix.service.DocumentServiceImpl.java

@Override
public String saveFileToApp(Integer appId, MultipartFile file) {
    if (appId == null || file == null) {
        log.warn("The document upload file failed to save, it had null input.");
        return null;
    }/*  ww w .  ja  v a2s.  c o m*/

    Application application = applicationDao.retrieveById(appId);

    if (application == null) {
        log.warn("Unable to retrieve Application - document save failed.");
        return null;
    }

    if (!contentTypeService.isValidUpload(file.getContentType())) {
        log.warn("Invalid filetype for upload: " + file.getContentType());
        return null;
    }

    Document doc = new Document();
    String fileFullName = file.getOriginalFilename();
    doc.setApplication(application);
    doc.setName(getFileName(fileFullName));
    doc.setType(getFileType(fileFullName));
    if (!doc.getType().equals("json")) {
        doc.setContentType(contentTypeService.translateContentType(file.getContentType()));
    } else {
        doc.setContentType(contentTypeService.translateContentType("json"));
    }

    try {
        Blob blob = new SerialBlob(file.getBytes());
        doc.setFile(blob);

        List<Document> appDocs = application.getDocuments();
        if (appDocs == null)
            appDocs = new ArrayList<Document>();
        appDocs.add(doc);

        documentDao.saveOrUpdate(doc);
        applicationDao.saveOrUpdate(application);

    } catch (SQLException | IOException e) {
        log.warn("Unable to save document - exception occurs.");
        return null;
    }

    return fileFullName;
}

From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * loads the image from given image file.
 * //from  w  w  w  .  j a  va2  s  .com
 * @param staff - Staff
 * @throws IOException - detail exception during file processing
 */
private void uploadImage(Staff staff) throws IOException {

    if (staff.getMultipartFile() != null) {
        MultipartFile multipartFile = staff.getMultipartFile();
        if (multipartFile.getSize() > 0) {
            staff.setPhoto(multipartFile.getBytes());
        }

    }
}