Example usage for org.springframework.web.multipart MultipartHttpServletRequest getSession

List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getSession

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartHttpServletRequest getSession.

Prototype

public HttpSession getSession();

Source Link

Document

Returns the current session associated with this request, or if the request does not have a session, creates one.

Usage

From source file:com.igame.app.controller.Image2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    // HttpSession
    SecUser user = (SecUser) request.getSession().getAttribute("user");
    long appid = user.getAppid();
    log.debug("uploadPost called appid:{}" + appid);
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;/*from   w  w  w.  j  av a 2  s .  c om*/
    List<Image> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        log.debug("Uploading {}", mpf.getOriginalFilename());

        long id = IDGenerator.getKey();
        // String newFilenameBase = String.valueOf(id);
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = id + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + "app-" + appid + "/" + newFilename);

        if (!newFile.getParentFile().exists()) {
            log.debug(" {}" + newFile.getParentFile().getPath());
            newFile.getParentFile().mkdirs();
        }

        try {
            mpf.transferTo(newFile);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 150);
            String thumbnailFilename = id + "-thumbnail.png";
            File thumbnailFile = new File(storageDirectory + "/" + "app-" + appid + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);

            Image image = new Image();
            image.setId(id);
            image.setAppid(appid);
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            image = imageService.create(image);

            image.setUrl("app-" + appid + "/" + newFilename);
            image.setThumbnailUrl("app-" + appid + "/" + thumbnailFilename);
            image.setDeleteUrl("delete/" + image.getId());
            image.setDeleteType("DELETE");

            list.add(image);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:com.ace.erp.controller.sys.company.OrganizationController.java

@RequestMapping(value = "/company/upload", method = RequestMethod.POST)
@ResponseBody/* w w  w.j a va2 s. c  o m*/
public Response upload(@CurrentUser User user, String srcFile, MultipartHttpServletRequest request,
        HttpServletResponse response) {

    try {
        MultipartFile realPicFile = request.getFile(srcFile);
        InputStream in = realPicFile.getInputStream();
        String path = request.getSession().getServletContext().getRealPath("/");
        String fileName = user.getUsername() + "."
                + FilenameUtils.getExtension(realPicFile.getOriginalFilename());
        File f = new File(path + "/" + fileName);
        FileUtils.copyInputStreamToFile(in, f);
        logger.info("path : " + f.getAbsolutePath());
    } catch (Exception e) {
        logger.error("upload header picture error : ", e);
    }
    return null;
}

From source file:ru.langboost.controllers.file.FileController.java

@RequestMapping(value = "/file/upload", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody List<File> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    List<File> files = new LinkedList<>();
    Iterator<String> fileNamesIterator = request.getFileNames();
    MultipartFile multipartFile = null;//from  w  ww .  ja v a  2 s . c  om
    while (fileNamesIterator.hasNext()) {
        try {
            multipartFile = request.getFile(fileNamesIterator.next());
            String fileName = multipartFile.getOriginalFilename();
            String contentType = multipartFile.getContentType();
            byte[] source = multipartFile.getBytes();
            File file = new File(source, contentType, fileName);
            files.add(file);
        } catch (IOException ex) {
        }
    }
    request.getSession().setAttribute(SESSION_FILES_NAME, files);
    return files;
}

From source file:com.opendesign.service.UserService.java

/**
 * ?  2: ? /*from  w w  w .j  ava  2s.c om*/
 * 
 * @param userVO
 * @param request
 * @return
 */
@Transactional
public Map<String, Object> register2(UserVO userVO, MultipartHttpServletRequest request) throws Exception {

    Map<String, Object> resultMap = new HashMap<String, Object>();

    // === 1. session? user (??, passwd) .
    UserVO regUser = (UserVO) request.getSession().getAttribute(SessionKey.SESSION_REG_USER);
    boolean isValidSessionUser = (regUser != null && StringUtils.isNotEmpty(regUser.getEmail())
            && StringUtils.isNotEmpty(regUser.getPasswd()));

    /* ?? accesstoken ?   */
    if (!StringUtils.isEmpty(regUser.getFbAccessToken())) {
        isValidSessionUser = true;
    }

    if (!isValidSessionUser) {
        resultMap.put(RstConst.P_NAME, RstConst.V_FAIL);
        return resultMap;
    }
    userVO.setEmail(regUser.getEmail());
    // 
    userVO.setPasswd(CmnUtil.encryptPassword(regUser.getPasswd()));
    userVO.setFbAccessToken(regUser.getFbAccessToken());

    userVO.setSidoSeq(regUser.getSidoSeq());

    // set
    String sidoVal = (String) request.getParameter("sidoVal");
    int sidoSeq = Integer.parseInt(sidoVal);

    userVO.setSidoSeq(sidoSeq);

    LOGGER.debug(userVO);

    // 1.1 ?? ?:
    int emailCnt = dao.checkEmailDup(userVO);
    if (emailCnt > 0) {
        resultMap.put(RstConst.P_NAME, RstConst.V_EMAIL_DUP); // ?? 
        return resultMap;
    }
    // 1.2 ?  ?:
    int unameCnt = dao.checkUnameDup(userVO);
    if (unameCnt > 0) {
        resultMap.put(RstConst.P_NAME, RstConst.V_UNAME_DUP); // ?  ?
        return resultMap;
    }

    // === 2.  param 
    // 2.1 memberType
    String memberType = handleMemberType(userVO.getMemberTypeCheck());
    userVO.setMemberType(memberType);

    // 2.2 file 
    // 
    String fileUploadDbPath = CmnUtil.handleFileUpload(request, "imageUrlFile", FileUploadDomain.USER_PROFILE);
    userVO.setImageUrl(fileUploadDbPath);

    // === 3. db 
    CmnUtil.setCmnDate(userVO);
    userVO.setPoint(DEFAULT_POINT); // default point
    dao.insertUser(userVO);

    // 3.1 ?  
    String[] memberCateCode = userVO.getMemberCateCode();
    if (!CmnUtil.isEmpty(memberCateCode)) {
        for (String code : memberCateCode) {
            MemberCategoryVO mcVO = new MemberCategoryVO();
            mcVO.setCategoryCode(code);
            mcVO.setMemberSeq(userVO.getSeq());
            CmnUtil.setCmnDate(mcVO);
            dao.insertMemberCategory(mcVO);
        }
    }

    // 4 ? session? 
    request.getSession().setAttribute(SessionKey.SESSION_LOGIN_USER, userVO);

    //
    resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS);
    return resultMap;
}

From source file:org.openmrs.module.radiology.web.controller.RadiologyObsFormController.java

/**
 * Save obs corresponding to given http servlet request, http servlet response, editReason, radiologyOrder, obs, obsErrors
 *  //from   w w w  .  jav a2  s  .  c o m
 * @param request the http servlet request with all parameters
 * @param response the http servlet response
 * @param editReason reason why the obs was edited
 * @param radiologyOrder radiology order corresponding to the obs
 * @param obs the obs to be changed
 * @param obsErrors the result of the parameter binding
 * @return ModelAndView populated with obs matching the given criteria
 * @should return redirecting model and view for not authenticated user
 * @should return populated model and view for complex obs
 * @should return populated model and view for invalid complex obs
 * @should populate model and view with obs for occuring Exception
 */
@RequestMapping(method = RequestMethod.POST, params = "saveComplexObs")
protected ModelAndView saveComplexObs(MultipartHttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "editReason", required = false) String editReason,
        @RequestParam(value = "orderId", required = true) RadiologyOrder radiologyOrder,
        @ModelAttribute("obs") Obs obs, BindingResult obsErrors) {

    if (Context.isAuthenticated()) {
        try {
            InputStream complexDataInputStream = openInputStreamForComplexDataFile(
                    request.getFile("complexDataFile"));
            obs = populateObsWithComplexData(request.getFile("complexDataFile"), obs, complexDataInputStream);
            if (isObsValidToSave(obs, obsErrors, editReason)) {
                obs = obsService.saveObs(obs, editReason);
                request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Obs.saved");
            } else {
                return populateModelAndView(radiologyOrder, obs, editReason);
            }
            complexDataInputStream.close();
        } catch (Exception e) {
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
            return populateModelAndView(radiologyOrder, obs, editReason);
        }
    }
    return new ModelAndView("redirect:" + RADIOLOGY_OBS_FORM_URL + "orderId=" + obs.getOrder().getId()
            + "&obsId=" + obs.getId());
}