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.gallery.web.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response)
        throws IOException {
    log.info("UploadPost called...");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<ImageVO> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        String originalFilename = mpf.getOriginalFilename();
        if (originalFilename == null || StringUtils.isEmpty(originalFilename)) {
            originalFilename = UUID.randomUUID().toString() + ".jpg";
        }//from w w  w  .j a v a  2  s  . c  o  m
        log.info("Uploading {}", originalFilename);

        String newFilenameBase = "-" + UUID.randomUUID().toString();
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();
        if (contentType == null || StringUtils.isEmpty(contentType)) {
            contentType = "image/jpeg";
        }
        String newFilename = newFilenameBase;
        InputStream in = null;
        try {
            // Save Images
            // mpf.transferTo(newFile);
            in = new ByteArrayInputStream(mpf.getBytes());
            BufferedImage originalImage = ImageIO.read(in);

            // Save Original Image
            String filenameExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1,
                    originalFilename.length());
            ImageIO.write(originalImage, filenameExtension,
                    new File(storageDirectory + File.separatorChar + originalFilename));

            // Small Thumbnails
            BufferedImage thumbnail_small = Scalr.resize(originalImage, ThumbnailSize.SMALL_SIZE.getSize());
            compressImg(thumbnail_small,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.SMALL_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.SMALL_SIZE.getFormatName()),
                    ThumbnailSize.SMALL_SIZE.getCompressionQuality());

            // Medium Thumbnail
            BufferedImage thumbnail_medium = Scalr.resize(originalImage, ThumbnailSize.MEDIUM_SIZE.getSize());
            compressImg(thumbnail_medium,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.MEDIUM_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.MEDIUM_SIZE.getFormatName()),
                    ThumbnailSize.MEDIUM_SIZE.getCompressionQuality());

            // Big Thumbnails
            BufferedImage thumbnail_big = Scalr.resize(originalImage, ThumbnailSize.BIG_SIZE.getSize());
            compressImg(thumbnail_big,
                    new File(storageDirectory + File.separatorChar + ThumbnailSize.BIG_SIZE.getId()
                            + newFilenameBase + "." + ThumbnailSize.BIG_SIZE.getFormatName()),
                    ThumbnailSize.BIG_SIZE.getCompressionQuality());

            log.info("EmotionParser...");
            // ImageEntity entity =
            // EmotionParser.parse(ImageIO.read(newFile));
            ImageEntity entity = new ImageEntity();
            entity.setName(originalFilename);
            entity.setNewFilename(newFilename);
            entity.setContentType(contentType);
            entity.setSize(mpf.getSize());
            imageDao.save(entity);

            ImageVO imageVO = new ImageVO(entity);
            imageVO.setId(entity.getId());
            imageVO.setUrl("/picture/" + entity.getId());
            imageVO.setThumbnailUrl("/thumbnail/" + entity.getId());
            imageVO.setDeleteUrl("/delete/" + entity.getId());
            imageVO.setEmotionUrl("/emotion/" + entity.getId());
            imageVO.setDeleteType("DELETE");

            list.add(imageVO);
        } catch (IOException e) {
            log.error("Could not upload file " + originalFilename, e);
        } finally {
            in.close();
        }
    }
    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:outfox.dict.contest.service.ContestService.java

/**
 * ?//from   ww  w.  ja  va2  s .  c o  m
 * @param req
 * @param params
 * @return
 */
public String addSingerForCityContest(HttpServletRequest req, SceneContestEntity sceneContest,
        MultipartFile file) {
    String userId = ContestUtil.getUserId(req);

    try {
        // 1: ???
        if (!verifyAuthority(userId)) {
            return Result.PERMISSION_DENIED.json(null, null);
        }

        // 2: 
        String photoUrl = ImageUtils.imageToOimage(file.getBytes());
        sceneContest.setPhotoUrl(photoUrl);
        sceneContest.setPeriod(ContestConsts.PERIOD);
        contestDAO.addSingerInfoForCityContest(sceneContest);

        // 3 
        sceneContest.setRound1Id(ContestConsts.COMMENT_PREFIX + "round1_" + sceneContest.getId());
        sceneContest.setRound2Id(ContestConsts.COMMENT_PREFIX + "round2_" + sceneContest.getId());
        sceneContest.setRound3Id(ContestConsts.COMMENT_PREFIX + "round3_" + sceneContest.getId());
        contestDAO.updateSingerInfoForCityContest(sceneContest);
        return Result.SUCCESS.json(null, null);
    } catch (Exception e) {
        LOG.error("ContestService.addSingerForCityContest error...", e);
    }
    return Result.SERVER_ERROR.json(null, null);
}

From source file:com.eastcom.hrmis.modules.emp.web.controller.api.EmployeeController.java

/**
 * ?/*from   ww  w  .  j  a  v a2 s.c  o m*/
 * @param session
 * @param request
 * @param params
 * @return
 */
@OperationLog(content = "?", type = OperationType.VIEW)
@ResponseBody
@RequestMapping(value = "/headerUpload")
public AjaxJson headerUpload(HttpSession session, HttpServletRequest request,
        @RequestParam Map<String, Object> params) {
    logger.info("--?--");
    AjaxJson json = new AjaxJson();
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multiRequest.getFile("file");
    try {
        String id = StringUtils.defaultIfBlank((String) params.get("id"), "0");
        Employee employee = employeeService.get(id);
        if (employee != null) {
            employee.setHeaderImg(file.getBytes());
            employee.setHeaderImgName(employee.getId() + "-" + Math.random() + "." + StringUtils.lowerCase(
                    file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1)));
            employeeService.saveOrUpdate(employee);

            //,
            String directoryUrl = Global.getConfig("tmp.user_header.url") + employee.getId();
            File oldDirectory = new File(getRealPath(session) + directoryUrl);
            if (oldDirectory.exists()) {
                FileUtils.cleanDirectory(oldDirectory);
            }

            json.setMessage("?");
            json.setSuccess(true);
        }
    } catch (Exception e) {
        e.printStackTrace();
        json.setMessage("??!");
        json.setSuccess(false);
    }
    return json;
}

From source file:se.gothiaforum.controller.actorsform.AddImageController.java

/**
 * Adds the logo to the image gallery for the actors organization.
 * /*w w  w. j  a v  a 2  s .  co  m*/
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws Exception
 *             the exception
 */
@RequestMapping(params = "action=addActorImage")
public void addActorImage(ActionRequest request, ActionResponse response, Model model) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    ActorArticle actorArticle = actorsService.getActorsArticle(themeDisplay);
    long actorGroupId = actorArticle.getGroupId();
    long userId = themeDisplay.getUserId();

    List<String> errors = new ArrayList<String>();

    if (request instanceof MultipartActionRequest) {
        MultipartActionRequest multipartRequest = (MultipartActionRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");

        if (multipartFile.getSize() == 0) {

            ServiceContext serviceContext = ServiceContextFactory.getInstance(JournalArticle.class.getName(),
                    request);

            String imageURL = actorsService
                    .getImageURL((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY));

            actorArticle.setImageUuid(imageURL);

            JournalArticle article = actorsService.updateActors(actorArticle, userId, serviceContext,
                    actorArticle.getTagsStr(), themeDisplay.getScopeGroupId());

            Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
            indexer.reindex(article);

        } else {

            String originalFileName = multipartFile.getOriginalFilename();
            String mimeType = multipartFile.getContentType();

            validator.validate(multipartFile, errors);

            if (!errors.isEmpty()) {
                model.addAttribute("errorList", errors);
                response.setRenderParameter("view", "showImageActorsForm");
            } else {

                byte[] logoInByte = multipartFile.getBytes();

                DLFileEntry image = actorsService.addImage(userId, actorGroupId, originalFileName, logoInByte,
                        mimeType, themeDisplay.getPortletDisplay().getRootPortletId());

                ServiceContext serviceContext = ServiceContextFactory
                        .getInstance(JournalArticle.class.getName(), request);

                // Assume there is no parent folder. Otherwise we would need to concatenate a like "{parentFolderId}/{image.getFolderId}
                String imageUrl = ActorsServiceUtil.getImageUrl(image);

                actorArticle.setImageUuid(imageUrl);

                JournalArticle article = actorsService.updateActors(actorArticle, userId, serviceContext,
                        actorArticle.getTagsStr(), themeDisplay.getScopeGroupId());

                Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
                indexer.reindex(article);

            }
        }
    }
}

From source file:com.eastcom.hrmis.modules.emp.web.controller.api.EmployeeController.java

/**
 * ??//from   w  ww  . j a va  2 s  .  c  o m
 * @param request
 * @param response
 * @param plupload
 * @return
 */
@ResponseBody
@RequestMapping(value = "/contractHomeAnnexUpload")
public AjaxJson contractHomeAnnexUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
    logger.info("---??---");
    AjaxJson json = new AjaxJson();
    json.setMessage("?!");
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multiRequest.getFile("file");
    try {
        String employeeId = request.getParameter("employeeId");
        Employee employee = employeeService.get(employeeId);
        if (employee != null) {
            EmployeeContractHomeAnnex homeAnnex = new EmployeeContractHomeAnnex();
            homeAnnex.setAnnexContent(file.getBytes());
            homeAnnex.setAnnexName(file.getOriginalFilename());
            homeAnnex.setEmployee(employee);
            homeAnnexService.save(homeAnnex);
        }
        json.setMessage("?");
        json.setSuccess(true);
    } catch (Exception e) {
        e.printStackTrace();
        json.setMessage("??!");
        json.setSuccess(false);
    }
    return json;
}

From source file:com.eastcom.hrmis.modules.emp.web.controller.api.EmployeeController.java

/**
 * ??//from www .  j  av  a2s .c  o  m
 * @param request
 * @param response
 * @param plupload
 * @return
 */
@ResponseBody
@RequestMapping(value = "/contractFinalAnnexUpload")
public AjaxJson contractFinalAnnexUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
    logger.info("---??---");
    AjaxJson json = new AjaxJson();
    json.setMessage("?!");
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multiRequest.getFile("file");
    try {
        String employeeId = request.getParameter("employeeId");
        Employee employee = employeeService.get(employeeId);
        if (employee != null) {
            EmployeeContractFinalAnnex finalAnnex = new EmployeeContractFinalAnnex();
            finalAnnex.setAnnexContent(file.getBytes());
            finalAnnex.setAnnexName(file.getOriginalFilename());
            finalAnnex.setEmployee(employee);
            finalAnnexService.save(finalAnnex);
        }
        json.setMessage("?");
        json.setSuccess(true);
    } catch (Exception e) {
        e.printStackTrace();
        json.setMessage("??!");
        json.setSuccess(false);
    }
    return json;
}

From source file:fr.xebia.cocktail.CocktailManager.java

/**
 * TODO use PUT instead of POST/*from  ww w.j a v a 2 s . c o m*/
 *
 * @param id    id of the cocktail
 * @param photo to associate with the cocktail
 * @return redirection to display cocktail
 */
@RequestMapping(value = "/cocktail/{id}/photo", method = RequestMethod.POST)
public String updatePhoto(@PathVariable String id, @RequestParam("photo") MultipartFile photo) {

    if (!photo.isEmpty()) {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("photo",
                        "Skip file with unsupported extension '" + photo.getOriginalFilename() + "'");
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                Map metadata = new TreeMap();
                metadata.put("Content-Length", Arrays.asList(new String[] { "" + photoSize }));
                metadata.put("Content-Type", Arrays.asList(new String[] { contentType }));
                metadata.put("Cache-Control", Arrays.asList(
                        new String[] { "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS) }));

                /*    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentLength(photoSize);
                    objectMetadata.setContentType(contentType);
                    objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));*/
                String photoUrl = fileStorageService.storeFile(photo.getBytes(), metadata);

                Cocktail cocktail = cocktailRepository.get(id);
                logger.info("Saved {}", photoUrl);
                cocktail.setPhotoUrl(photoUrl);
                cocktailRepository.update(cocktail);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/cocktail/" + id;
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*from  ww w. ja  va 2 s.  c om*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:outfox.dict.contest.service.ContestService.java

/**
 * /* w  ww .  j  a va 2s . c o  m*/
 * @param file
 * @param callback
 * @return
 */
public String uploadAudio(HttpServletRequest req, MultipartFile file, RequestParams params) {
    String callback = params.getCallback(); // jsonp?
    String userId = ContestUtil.getUserId(req); // ?
    boolean limitLogin = params.isLimitLogin(); // ??
    // 
    if (StringUtils.isBlank(userId) && limitLogin) {
        return Result.NOT_LOGIN.json(null, callback);
    }

    try {
        String audiourl = FileUtils.uploadFile2Nos(file.getBytes());
        JSONObject dataObj = new JSONObject();
        dataObj.put("audiourl", audiourl);
        return Result.SUCCESS.json(dataObj, callback);
    } catch (Exception e) {
        LOG.error("ContestService.uploadAudio error...", e);
    }
    return Result.SERVER_ERROR.json(null, callback);
}

From source file:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/upload/{ownerId}/{objectId}", method = RequestMethod.POST)
public @ResponseBody void uploadAvatar(@PathVariable String ownerId, @PathVariable String objectId,
        @RequestParam("data") MultipartFile data, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }//from  w  w  w  .j  a  va 2s .c om
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_ADD, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    criteria = Criteria.where("resourceId").is(objectId).and("resourceType").is(Const.AUTH_RES_Child);
    Avatar avatar = storage.findOneData(Avatar.class, criteria, ownerId);
    if (avatar == null) {
        avatar = new Avatar();
        avatar.setOwnerId(ownerId);
        avatar.setObjectId(Utils.getUUID());
        avatar.setResourceId(objectId);
        avatar.setResourceType(Const.AUTH_RES_Child);
    }
    avatar.setContentType(data.getContentType());
    avatar.setImage(new Binary(data.getBytes()));
    if (logger.isInfoEnabled()) {
        logger.info(String.format("uploadAvatar[%s]:%s", ownerId, objectId));
    }
    storage.saveAvatar(avatar);
}