Java 类org.springframework.web.multipart.MultipartHttpServletRequest 实例源码

项目:forweaver2.0    文件:CodeController.java   
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(final HttpServletRequest request,Model model) throws UnsupportedEncodingException {
    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

    MultipartFile file = multiRequest.getFile("file");
    MultipartFile output = multiRequest.getFile("output");
    String tags = request.getParameter("tags");
    String content = request.getParameter("content");
    String url = request.getParameter("url");
    String name = file.getOriginalFilename();
    name = name.substring(0, name.indexOf('.'));
    if(tags == null || content.length() < 5 || content.length() >50 || file == null){ // 태그가 없을 때
        model.addAttribute("say", "잘못 입력하셨습니다!!!");
        model.addAttribute("url", "/code/");
        return "/alert";
    }
    List<String> tagList = this.tagService.stringToTagList(tags);
    Weaver weaver = this.weaverService.getCurrentWeaver();
    if(!this.codeService.add(new Code(weaver, name, content,url, tagList), file,output)){ // 태그가 없을 때
        model.addAttribute("say", "코드 업로드에 실패하였습니다! 압축파일을 확인하시거나 제대로된 소스파일인지 확인해주세요.");
        model.addAttribute("url", "/code/");
        return "/alert";
    }
    return "redirect:/code/";
}
项目:wavemaker-app-build-tools    文件:SwaggerGenerator.java   
public Swagger generate(){
    Swagger swagger = null;

    FilterableClassScanner classScanner = new FilterableClassScanner();
    classScanner.includePackage(basePackage);
    FilterableModelScanner modelScanner = new FilterableModelScanner();
    modelScanner.excludePackage("javax.servlet.http");

    final SwaggerConfiguration.Builder builder = new SwaggerConfiguration.Builder("", classScanner);
    builder.setModelScanner(modelScanner);

    if(classLoader != null) {
        builder.setClassLoader(classLoader);
    } else{
        builder.setClassLoader(Thread.currentThread().getContextClassLoader());
    }

    if(swaggerInfo != null) {
        builder.setInfo(swaggerInfo);
    } else {
        builder.setInfo(new Info());
    }

    swagger = ResourceClassLoaderUtils.runInClassLoaderContext(new WMCallable<Swagger>() {
        @Override
        public Swagger call() {
            builder.addParameterResolver(Pageable.class, new PageParameterResolver());
            builder.addParameterResolver(MultipartFile.class, new MultiPartFileResolver());
            builder.addParameterResolver(MultipartHttpServletRequest.class, new MultiPartRequestResolver());
            builder.addParameterResolver(HttpServletRequest.class, new ServletMetaTypesResolver());
            builder.addParameterResolver(HttpServletResponse.class, new ServletMetaTypesResolver());
            SwaggerParser swaggerParser = new SpringSwaggerParser(builder.build());
            return swaggerParser.generate();
        }
    }, classLoader);

    return swagger;
}
项目:sjk    文件:MoFeaturedController.java   
@RequestMapping(value = "/save.d", produces = "application/json;charset=UTF-8")
public String saveOrUpdate(MultipartHttpServletRequest multipartReq, MoFeatured moFeatured, Model model) {
    try {
        if (moFeatured.getPicType() == 3) {
            String bigPics = StringUtils.defaultIfEmpty(moFeatured.getBigPics(), "").replace(",,", "");
            moFeatured.setBigPics(StringUtils.stripEnd(StringUtils.stripStart(bigPics, ","), ","));
        } else {
            String pics = StringUtils.defaultIfEmpty(moFeatured.getPics(), "").replace(",,", "");
            moFeatured.setPics(StringUtils.stripEnd(StringUtils.stripStart(pics, ","), ","));
        }
        moFeaturedService.saveOrUpdate(multipartReq, moFeatured);
        model.addAttribute("rstCode", 0);
    } catch (Exception e) {
        model.addAttribute("rstCode", 1);
    }
    return "/moFeatured/save";
}
项目:spring-boot-excel-plugin    文件:ExcelRequestResponseBodyHandler.java   
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
    MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

    ExcelRequestBody annotation = parameter.getParameterAnnotation(ExcelRequestBody.class);
    if (multipartRequest != null) {
        List<Object> result = new ArrayList<>();
        List<MultipartFile> files = multipartRequest.getFiles(annotation.name());
        for (MultipartFile file : files) {
            if (converters.supportsExcelType(annotation.type())) {
                List<?> part = converters.fromExcel(annotation, file.getInputStream());
                result.addAll(part);
            }
        }
        return result;
    }
    return null;

}
项目:Educational-Management-System    文件:TeacherTableController.java   
@RequestMapping(value="uploadexcle",method={RequestMethod.GET,RequestMethod.POST})
public  String  uploadExcel(HttpServletRequest request, Model model) throws Exception {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    InputStream in =null;
    List<List<Object>> list = null;
    MultipartFile file = multipartRequest.getFile("upfile");
    if(file.isEmpty()){
        throw new Exception("文件不存在!");
    }
    in = file.getInputStream();
    list = teacherService.getListByExcel(in,file.getOriginalFilename());
    in.close();
    model.addAttribute("list",list);
    return "admin/teacher/upload";
}
项目:lams    文件:RequestPartServletServerHttpRequest.java   
/**
 * Create a new instance.
 * @param request the current request
 * @param partName the name of the part to adapt to the {@link ServerHttpRequest} contract
 * @throws MissingServletRequestPartException if the request part cannot be found
 * @throws IllegalArgumentException if MultipartHttpServletRequest cannot be initialized
 */
public RequestPartServletServerHttpRequest(HttpServletRequest request, String partName)
        throws MissingServletRequestPartException {

    super(request);

    this.multipartRequest = asMultipartRequest(request);
    this.partName = partName;

    this.headers = this.multipartRequest.getMultipartHeaders(this.partName);
    if (this.headers == null) {
        if (request instanceof MultipartHttpServletRequest) {
            throw new MissingServletRequestPartException(partName);
        }
        else {
            throw new IllegalArgumentException(
                    "Failed to obtain request part: " + partName + ". " +
                    "The part is missing or multipart processing is not configured. " +
                    "Check for a MultipartResolver bean or if Servlet 3.0 multipart processing is enabled.");
        }
    }
}
项目:tianti    文件:UploadController.java   
@RequestMapping("/ajax/upload_file")
@ResponseBody
public AjaxResult ajaxUploadFile(HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    AjaxResult ajaxResult = new AjaxResult();
    ajaxResult.setSuccess(false);
    try {

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile multipartFile = null;
        String fileName = null;
        for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
            multipartFile = set.getValue();// 文件名
        }
        fileName = this.storeIOc(multipartRequest, multipartFile);

        ajaxResult.setData(fileName);
        ajaxResult.setSuccess(true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ajaxResult;
}
项目:springbootWeb    文件:UploadUtil.java   
/**
 * 上传文件.
 * @param request 请求
 * @param paraName 文件参数名
 * @param baseDir 基本目录
 * @param dir 文件相对目录
 * @return 文件名
 * @throws IOException IO异常
 */
public static List<String> upload(HttpServletRequest request, String paraName, String baseDir, String dir) throws IOException {
    List<String> fileNames = null;
    if (request instanceof MultipartHttpServletRequest) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles(paraName);
        fileNames = new ArrayList<>(files.size());
        String originalName;
        String newName;
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            File dic = new File(baseDir + dir);
            if (!dic.exists()) {
                dic.mkdirs();
            }
            originalName = file.getOriginalFilename();
            newName = UUIDGenerator.getFileName() + originalName.substring(originalName.lastIndexOf("."));
            Files.copy(file.getInputStream(), Paths.get(baseDir + dir + "/" + newName));
            fileNames.add(dir + "/" + newName);
        }
    }
    return fileNames;
}
项目:sjk    文件:AppController.java   
@RequestMapping(value = "/rolling/upd-logo.d", produces = "application/json;charset=UTF-8")
@ResponseBody
public String updateLogo(MultipartHttpServletRequest multipartReq, @RequestParam int id) {
    JSONObject output = new JSONObject();
    JSONObject server = new JSONObject();
    output.put("result", server);
    try {
        appService.updateLogo(multipartReq, id);
        server.put("code", SvrResult.OK.getCode());
        server.put("msg", SvrResult.OK.getMsg());
    } catch (Exception e) {
        logger.error("Exception", e);
        server.put("code", SvrResult.ERROR.getCode());
        server.put("msg", SvrResult.ERROR.getMsg());
    }
    return output.toJSONString(jsonStyle);
}
项目:sjk    文件:MetroController.java   
@RequestMapping(value = "/save.d", produces = "application/json;charset=UTF-8")
// @ResponseBody
public String saveOrUpdate(MultipartHttpServletRequest multipartReq, Metro metro) {
    logger.debug("receiving...metro save.");
    JSONObject output = new JSONObject();
    JSONObject server = new JSONObject();
    output.put("result", server);
    try {
        String pics = StringUtils.defaultIfEmpty(metro.getPics(), "").replace(",,", "");
        metro.setPics(StringUtils.stripEnd(StringUtils.stripStart(pics, ","), ","));
        metroService.saveOrUpdate(multipartReq, metro);
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return "/metro/save";
}
项目:sjk    文件:MarketAppServiceImpl.java   
public void updateIndexImg(MultipartHttpServletRequest multipartReq, MarketApp marketApp) throws IOException,
        MalformedURLException, URISyntaxException {
    int id = marketApp.getId();

    // 大游戏首页图片.浏览器上传用户本地文件 或 下载远端服务器 图片.
    String indexImgUrlBak = multipartReq.getParameter("oldIndexImgUrl"); // app.getIndexImgUrl();
    boolean needToDeleteIndexImgUrlBak = false;
    String remoteIndexImgUrl = multipartReq.getParameter("remoteIndexImgUrl");
    MultipartFile file = multipartReq.getFile("indexImgFile");
    String subPath = null;
    if (file != null && !file.isEmpty()) {
        subPath = attachmentService.saveMarketAppFile(id, file);
    } else if (StringUtils.isNotBlank(remoteIndexImgUrl)) {
        // 拉取图片.
        subPath = attachmentService.saveMarketAppFile(id, remoteIndexImgUrl);
    }
    if (StringUtils.isNotBlank(subPath)) {
        String indexImgUrl = PathUtils.concate(appConfig.getDestBigGameUploadBaseurl(), subPath);
        marketApp.setIndexImgUrl(indexImgUrl);
        saveOrUpdate(marketApp);
        needToDeleteIndexImgUrlBak = true;
    }
    if (appConfig.isDeleteUploadImageFile() && StringUtils.isNotBlank(indexImgUrlBak) && needToDeleteIndexImgUrlBak) {
        attachmentService.deleteFile(indexImgUrlBak);
    }
}
项目:sjk    文件:MarketAppServiceImpl.java   
public void updateLogo(MultipartHttpServletRequest multipartReq, MarketApp marketApp) throws IOException,
        MalformedURLException, URISyntaxException {
    int id = marketApp.getId();
    // logo. 浏览器上传用户本地文件 或 下载远端服务器 图片.
    String logoUrlBak = multipartReq.getParameter("oldLogoUrl");// app.getLogoUrl();
    boolean needToDeleteLogoUrlBak = false;
    String remoteLogoUrl = multipartReq.getParameter("remoteLogoUrl");
    MultipartFile file = multipartReq.getFile("logoFile");
    String logoSubPath = null;
    if (file != null && !file.isEmpty()) {
        logoSubPath = attachmentService.saveMarketAppFile(id, file);
    } else if (StringUtils.isNotBlank(remoteLogoUrl)) {
        // 拉取图片.
        logoSubPath = attachmentService.saveMarketAppFile(id, remoteLogoUrl);
    }
    if (StringUtils.isNotBlank(logoSubPath)) {
        String logoUrl = PathUtils.concate(appConfig.getDestBigGameUploadBaseurl(), logoSubPath);
        marketApp.setLogoUrl(logoUrl);
        saveOrUpdate(marketApp);
        needToDeleteLogoUrlBak = true;
    }
    if (appConfig.isDeleteUploadImageFile() && StringUtils.isNotBlank(logoUrlBak) && needToDeleteLogoUrlBak) {
        attachmentService.deleteFile(logoUrlBak);
    }
}
项目:sjk    文件:AppServiceImpl.java   
public void updateIndexImg(MultipartHttpServletRequest multipartReq, App app) throws IOException,
        MalformedURLException, URISyntaxException {
    int id = app.getId();

    // 大游戏首页图片.浏览器上传用户本地文件 或 下载远端服务器 图片.
    String indexImgUrlBak = multipartReq.getParameter("oldIndexImgUrl"); // app.getIndexImgUrl();
    boolean needToDeleteIndexImgUrlBak = false;
    String remoteIndexImgUrl = multipartReq.getParameter("remoteIndexImgUrl");
    MultipartFile file = multipartReq.getFile("indexImgFile");
    String subPath = null;
    if (file != null && !file.isEmpty()) {
        subPath = attachmentService.saveFile(id, file);
    } else if (StringUtils.isNotBlank(remoteIndexImgUrl)) {
        // 拉取图片.
        subPath = attachmentService.saveFile(id, remoteIndexImgUrl);
    }
    if (StringUtils.isNotBlank(subPath)) {
        String indexImgUrl = PathUtils.concate(appConfig.getDestUploadBaseurl(), subPath);
        app.setIndexImgUrl(indexImgUrl);
        saveOrUpdate(app);
        needToDeleteIndexImgUrlBak = true;
    }
    if (StringUtils.isNotBlank(indexImgUrlBak) && needToDeleteIndexImgUrlBak) {
        attachmentService.deleteFile(indexImgUrlBak);
    }
}
项目:sjk    文件:AppServiceImpl.java   
private List<AppAndTag> getAppTags(MultipartHttpServletRequest multipartReq) {
    List<AppAndTag> list = new ArrayList<AppAndTag>();
    String[] ids = multipartReq.getParameterValues("appTagId");
    String[] appIds = multipartReq.getParameterValues("appId");
    String[] tagNames = multipartReq.getParameterValues("tagName");
    String[] tagIds = multipartReq.getParameterValues("tagId");
    AppAndTag tag = null;
    if (ids != null && ids.length > 0) {
        for (int i = 0; i < ids.length; i++) {
            tag = new AppAndTag();
            tag.setId(Integer.valueOf(StringUtils.defaultIfEmpty(ids[i], "0")));
            tag.setAppId(Integer.valueOf(StringUtils.defaultIfEmpty(appIds[i], "0")));
            tag.setTagId(Integer.valueOf(StringUtils.defaultIfEmpty(tagIds[i], "0")));
            tag.setTagName(StringUtils.defaultIfEmpty(tagNames[i], ""));
            list.add(tag);
        }
    }
    return list;
}
项目:sjk    文件:MoTagRelationshipServiceImpl.java   
@Override
public void saveOrUpdate(MultipartHttpServletRequest multipartReq, MoTag tag) {
    tag.setImgUrl(StringUtils.isEmpty(tag.getImgUrl()) == true ? "" : tag.getImgUrl());
    tag.setBigPics(StringUtils.isEmpty(tag.getBigPics()) == true ? "" : tag.getBigPics());
    tag.setMediumPics(StringUtils.isEmpty(tag.getMediumPics()) == true ? "" : tag.getMediumPics());
    tag.setSmallPics(StringUtils.isEmpty(tag.getSmallPics()) == true ? "" : tag.getSmallPics());
    if (tag.getId() == 0) {
        moTagDao.save(tag);
    } else {
        moTagDao.update(tag);
    }
    // updateTagImgUrl(multipartReq, tag);
    updateBigPicsUrl(multipartReq, tag);
    updateSmallPicsUrl(multipartReq, tag);
    updateMediumPicsUrl(multipartReq, tag);
}
项目:stalactite    文件:FileController.java   
@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
public Res upload(MultipartHttpServletRequest request) {
    Res res = new Res();
    try {
        Iterator<String> it = request.getFileNames();
        while (it.hasNext()) {
            String uploadFile = it.next();
            MultipartFile file = request.getFile(uploadFile);
            FileUpload newFile = new FileUpload(file);
            System.out.println("==============");
            System.out.println(newFile);
            fileService.uploadFile(file);
        }
    } catch (Exception e) {
        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    res.setStatus(HttpStatus.OK);
    return res;
}
项目:Qihua    文件:ProductImgController.java   
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody JSONResponseBody upload(MultipartHttpServletRequest request) {
  try {
    MultipartFile attachment = request.getFile("file");
    if (attachment != null && attachment.getSize() > 0) {
      FileMeta meta = new FileMeta();
      meta.setId(request.getParameter("productId"));
      meta.setName(IdUtils.uuid2());
      meta.setSize(attachment.getSize());
      meta.setExtension(StringUtils.getFilenameExtension(attachment.getOriginalFilename()));
      meta.setBytes(attachment.getBytes());
      meta.setUrl(Constants.DEPLOY_URL + Constants.PRODUCT_IMG_UPLOAD_DIR);

      // File folder = new File(Constants.DEPLOY_URL + Constants.PRODUCT_UPLOAD_DIR );
      // folder.mkdir();

      return new JSONResponseBody(productService.uploadImg(meta));
    }
  } catch (Exception e) {
    log.error(ExceptionUtils.getStackTraceAsString(e));

    return new JSONResponseBody(false, e.getMessage());
  }

  return new JSONResponseBody();
}
项目:Qihua    文件:ProductImgController.java   
@RequestMapping(value = "/recommend/upload", method = RequestMethod.POST)
public @ResponseBody JSONResponseBody uploadRecommend(MultipartHttpServletRequest request) {
  try {
    MultipartFile attachment = request.getFile("file");
    if (attachment != null && attachment.getSize() > 0) {
      FileMeta meta = new FileMeta();
      meta.setId(request.getParameter("productId"));
      meta.setName(IdUtils.uuid2());
      meta.setSize(attachment.getSize());
      meta.setExtension(StringUtils.getFilenameExtension(attachment.getOriginalFilename()));
      meta.setBytes(attachment.getBytes());
      meta.setUrl(Constants.DEPLOY_URL + Constants.PRODUCT_IMG_UPLOAD_DIR);

      // File folder = new File(Constants.DEPLOY_URL + Constants.PRODUCT_UPLOAD_DIR );
      // folder.mkdir();

      return new JSONResponseBody(productService.uploadRecommendImg(meta));
    }
  } catch (Exception e) {
    log.error(ExceptionUtils.getStackTraceAsString(e));

    return new JSONResponseBody(false, e.getMessage());
  }

  return new JSONResponseBody();
}
项目:Qihua    文件:ProductImgBlockController.java   
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody JSONResponseBody upload(MultipartHttpServletRequest request) {
  try {
    String position = request.getParameter("position");

    MultipartFile attachment = request.getFile("file");
    if (attachment != null && attachment.getSize() > 0) {
      FileMeta meta = new FileMeta();
      meta.setId(request.getParameter("productId"));
      meta.setName(IdUtils.uuid2());
      meta.setSize(attachment.getSize());
      meta.setExtension(StringUtils.getFilenameExtension(attachment.getOriginalFilename()));
      meta.setBytes(attachment.getBytes());
      meta.setUrl(Constants.DEPLOY_URL + Constants.PRODUCT_IMG_UPLOAD_DIR);

      return new JSONResponseBody(productService.uploadImgBlock(meta, position));
    }
  } catch (Exception e) {
    log.error(ExceptionUtils.getStackTraceAsString(e));

    return new JSONResponseBody(false, e.getMessage());
  }

  return new JSONResponseBody();
}
项目:Qihua    文件:HomeController.java   
@RequestMapping(value = "/img/upload", method = RequestMethod.POST)
public @ResponseBody JSONResponseBody uploadCenter(MultipartHttpServletRequest request) {
  try {
    String position = request.getParameter("position");

    MultipartFile attachment = request.getFile("file");
    if (attachment != null && attachment.getSize() > 0) {
      FileMeta meta = new FileMeta();
      meta.setId(request.getParameter("productId"));
      meta.setName(IdUtils.uuid2());
      meta.setSize(attachment.getSize());
      meta.setExtension(StringUtils.getFilenameExtension(attachment.getOriginalFilename()));
      meta.setBytes(attachment.getBytes());
      meta.setUrl(Constants.DEPLOY_URL + Constants.PRODUCT_IMG_UPLOAD_DIR);

      return new JSONResponseBody(homeService.uploadImg(meta, position));
    }
  } catch (Exception e) {
    log.error(ExceptionUtils.getStackTraceAsString(e));

    return new JSONResponseBody(false, e.getMessage());
  }

  return new JSONResponseBody();
}
项目:spring4-understanding    文件:DispatcherServlet.java   
/**
 * Convert the request into a multipart request, and make multipart resolver available.
 * <p>If no multipart resolver is set, simply use the existing request.
 * @param request current HTTP request
 * @return the processed request (multipart wrapper if necessary)
 * @see MultipartResolver#resolveMultipart
 */
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
    if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
        if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
            logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
                    "this typically results from an additional MultipartFilter in web.xml");
        }
        else if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) instanceof MultipartException) {
            logger.debug("Multipart resolution failed for current request before - " +
                    "skipping re-resolution for undisturbed error rendering");
        }
        else {
            return this.multipartResolver.resolveMultipart(request);
        }
    }
    // If not returned before: return original request.
    return request;
}
项目:aramcomp    文件:SysHistoryController.java   
/**
 * 시스템이력 등록
 * 
 * @param sysHistoryVO
 */
@RequestMapping(value = "/sym/log/slg/insertSysHistory.do")
@Secured("ROLE_ADMIN")
public String insertSysHistory(
        MultipartHttpServletRequest multiRequest, 
        @ModelAttribute SysHistoryVO sysHistoryVO, 
        BindingResult bindingResult,
        ModelMap model) 
throws Exception {

    beanValidator.validate(sysHistoryVO, bindingResult);
    if (bindingResult.hasErrors()) {
        return WebUtil.adjustViewName("/sym/log/slg/SysHistRegist");
    }

    // 첨부파일 관련 첨부파일ID 생성
    sysHistoryVO.setAtchFileId(fileMngUtil.insertMultiFile(multiRequest, "SHF_"));

    LoginVO loginVO = (LoginVO) UserDetailsHelper.getAuthenticatedUser();
    sysHistoryVO.setFrstRegisterId(loginVO.getUniqId());

    sysHistoryService.insertSysHistory(sysHistoryVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
       return WebUtil.redirectJsp(model, "/sym/log/slg/listSysHistory.do");
}
项目:aramcomp    文件:SysHistoryController.java   
/**
 * 시스템이력 수정
 * 
 * @param sysHistoryVO
 */
@RequestMapping(value = "/sym/log/slg/updateSysHistory.do")
@Secured("ROLE_ADMIN")
public String updateSysHistory(
        MultipartHttpServletRequest multiRequest, 
        @ModelAttribute SysHistoryVO sysHistoryVO, 
        BindingResult bindingResult, 
        ModelMap model) 
throws Exception {

    beanValidator.validate(sysHistoryVO, bindingResult);
    if (bindingResult.hasErrors()) {
        return WebUtil.adjustViewName("/sym/log/slg/SysHistEdit");
    }

    // 첨부파일 관련 ID 생성 start....
    String atchFileId = sysHistoryVO.getAtchFileId();
    sysHistoryVO.setAtchFileId(fileMngUtil.updateMultiFile(multiRequest, "SHF_", atchFileId));

    sysHistoryService.updateSysHistory(sysHistoryVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.update"));
       return WebUtil.redirectJsp(model, "/sym/log/slg/listSysHistory.do");
}
项目:aramcomp    文件:AnnvrsryManageController.java   
/**
 * 기념일일괄등록화면 호출 및 기념일일괄등록처리 프로세스
 * 
 * @param annvrsryManageVO
 */
@RequestMapping(value = "/uss/ion/ans/listAnnvrsryBndePopup.do")
public String listAnnvrsryBndePopup(
        HttpServletRequest request, 
        @ModelAttribute AnnvrsryManageVO annvrsryManageVO,
        ModelMap model) 
throws Exception {

    String message = "";

    String sCmd = request.getParameter("cmd") == null ? "" : request.getParameter("cmd"); // 상세정보 구분
    if (sCmd.equals("bnde")) {
        final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

        for (MultipartFile file : multiRequest.getFileMap().values()) {
            if (!"".equals(file.getOriginalFilename())) {
                model.addAttribute("resultList", annvrsryManageService.selectAnnvrsryManageBnde(file.getInputStream()));
            } else {
                message = MessageHelper.getMessage("fail.common.msg");
            }
        }
        model.addAttribute("message", message);
    }

    return WebUtil.adjustViewName("/uss/ion/ans/AnnvrsryBndeListPopup");
}
项目:aramcomp    文件:RwardManageController.java   
/**
 * 포상관리정보를 신규로 등록한다.
 * 
 * @param rwardManageVO
 */
@RequestMapping(value = "/uss/ion/rwd/insertRward.do")
public String insertRward(
        MultipartHttpServletRequest multiRequest, 
        @ModelAttribute RwardManageVO rwardManageVO, 
        BindingResult bindingResult, 
        ModelMap model) 
throws Exception {

    beanValidator.validate(rwardManageVO, bindingResult); // validation 수행
    if (bindingResult.hasErrors()) {
        return WebUtil.adjustViewName("/uss/ion/rwd/RwardRegist");
    } 

    // 첨부파일 관련 첨부파일ID 생성
    rwardManageVO.setAtchFileId(fileMngUtil.insertMultiFile(multiRequest, "RWD_"));

    LoginVO loginVO = (LoginVO) UserDetailsHelper.getAuthenticatedUser();
    rwardManageVO.setFrstRegisterId(loginVO.getUniqId()); // 최초등록자ID

    rwardManageService.insertRwardManage(rwardManageVO);

    model.addAttribute("message", MessageHelper.getMessage("success.common.insert"));
       return WebUtil.redirectJsp(model, "/uss/ion/rwd/listRward.do");
}
项目:S4S4H4    文件:FileController.java   
@RequestMapping(value = "Upload")
public String Upload(HttpServletRequest request) throws Exception {
    // ת��ΪMultipartHttpRequest
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    // ����ϴ����ļ�������ǰ̨��name���Ƶõ��ϴ����ļ���
    MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
    List<MultipartFile> files = multiValueMap.get("clientFile");
    //MultipartFile file = multipartRequest.getFile("clientFile");
    if (!files.isEmpty()) {
        //������Ϳ��Զ�file���д����ˣ����Ը����Լ�����������浽���ݿ���߷�������ij���ļ���
    /*for(MultipartFile file :files)
     {
         fileService.upload(file);
     }*/
        //ʹ��forEach ��Lambda ʵ��
        files.forEach(f -> fileService.upload(f));
    }
    return "Success";
}
项目:GeneralCompanyProject    文件:UserService.java   
public String saveImage(MultipartHttpServletRequest request) throws IOException {
    UploadedFile ufile;
    Iterator<String> itr =  request.getFileNames();
    MultipartFile mpf = request.getFile(itr.next());

    String name = Calendar.getInstance().getTimeInMillis() + "";
    String type = "jpg";
    String originName = mpf.getOriginalFilename();
    if (originName.contains(".")) {
        String[] names = originName.split("\\.");
        type = names[1];
    }
    ufile = new UploadedFile(mpf.getBytes(), name + "." + type, mpf.getContentType(),
            mpf.getBytes().length);
    String imagePath = "http://" + request.getServerName() + ":" + request.getServerPort() + "/user/image/" +
            name + "/" + type;
    return imagePath;
}
项目:aramcomp    文件:SynchrnServerController.java   
/**
 * 동기화 대상 파일을 업로드 한다.
 * 
 * @param synchrnServerVO
 */
@RequestMapping(value = "/utl/sys/ssy/uploadFile.do")
@Secured("ROLE_ADMIN")
public String uploadFile(
        MultipartHttpServletRequest multiRequest, 
        @ModelAttribute SynchrnServerVO synchrnServerVO,
        ModelMap model) 
throws Exception {

    MultipartFile multipartFile = multiRequest.getFile("file");
    String fileName = multipartFile.getOriginalFilename();

    synchrnServerService.writeFile(multipartFile, fileName, uploadDir, synchrnServerVO);

    return WebUtil.redirectJsp(model, "/utl/sys/ssy/listSynchrnServer.do");
}
项目:forweaver2.0    文件:CodeController.java   
@RequestMapping(value = "/{codeID}/add-repost", method = RequestMethod.POST)
public String addRepost(@PathVariable("codeID") int codeID,
        HttpServletRequest request,Model model) throws UnsupportedEncodingException {

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

    final Map<String, MultipartFile> files = multiRequest.getFileMap();

    String content = request.getParameter("content");
    Weaver weaver = this.weaverService.getCurrentWeaver();
    Code code = this.codeService.get(codeID,true);

    if(code == null || weaver == null || content.equals("")) {
        model.addAttribute("say", "잘못 입력하셨습니다!!!");
        model.addAttribute("url", "/code/"+codeID);
        return "/alert";
    }

    ArrayList<Data> datas = new ArrayList<Data>();
    for (MultipartFile file : files.values()) {
        if(!file.isEmpty())
            datas.add(new Data(this.dataService.getObjectID(file.getOriginalFilename(), weaver),file,weaver));
    }

    RePost rePost = new RePost(code,
            weaver,
            content);
    this.rePostService.add(rePost,datas);
    code.setRePostCount(code.getRePostCount()+1);
    code.setRecentRePostDate(rePost.getCreated());
    this.codeService.update(code);

    return "redirect:/code/"+codeID;
}
项目:forweaver2.0    文件:CodeController.java   
@RequestMapping(value="/{codeID}/{rePostID}/update", method = RequestMethod.POST)
public String update(@PathVariable("codeID") int codeID, @PathVariable("rePostID") int rePostID,HttpServletRequest request,Model model) throws UnsupportedEncodingException {

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = multiRequest.getFileMap();
    ArrayList<Data> datas = new ArrayList<Data>();
    Code code = this.codeService.get(codeID,true);
    RePost rePost = this.rePostService.get(rePostID);
    String content = request.getParameter("content");
    Weaver weaver = this.weaverService.getCurrentWeaver();
    String remove = request.getParameter("remove");
    if(code == null || rePost == null || content.length() < 5 ||
            rePost.getOriginalCode().getCodeID() != code.getCodeID()){
        model.addAttribute("say", "잘못 입력하셨습니다!!!");
        model.addAttribute("url", "/code/"+codeID);
        return "/alert";
    }

    if(!rePost.getWriter().equals(weaver) &&
            !this.tagService.validateTag(code.getTags(),weaver)){ // 태그에 권한이 없을때
        model.addAttribute("say", "권한이 없습니다!!!");
        model.addAttribute("url", "/code/"+codeID);
        return "/alert";
    }

    for (MultipartFile file : files.values())
        if(!file.isEmpty()){
            String fileID= this.dataService.getObjectID(file.getOriginalFilename(), weaver);
            if(!fileID.equals(""))
                datas.add(new Data(fileID,file,weaver));
        }

    rePost.setContent(content);
    this.rePostService.update(rePost,datas,remove.split("@"));

    return "redirect:/code/"+codeID;
}
项目:forweaver2.0    文件:PostController.java   
@RequestMapping(value = "/{postID}/add-repost", method = RequestMethod.POST)
public String addRepost(@PathVariable("postID") int postID,HttpServletRequest request,Model model) throws UnsupportedEncodingException {

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

    final Map<String, MultipartFile> files = multiRequest.getFileMap(); 

    String content = request.getParameter("content");
    Post post = postService.get(postID);
    Weaver weaver = weaverService.getCurrentWeaver();


    if(!post.getWriter().equals(weaver) && !tagService.validateTag(post.getTags(),weaver) || 
            weaver == null || post == null || content.equals("")) {
        model.addAttribute("say", "잘못 입력하셨습니다!!!");
        model.addAttribute("url", "/community/"+postID);
        return "/alert";
    }

    ArrayList<Data> datas = new ArrayList<Data>();
    for (MultipartFile file : files.values()) 
        if(!file.isEmpty()){
            String fileID= dataService.getObjectID(file.getOriginalFilename(), weaver);
            if(!fileID.equals(""))
                datas.add(new Data(fileID,file,weaver));
        }

    RePost rePost = new RePost(post,weaver,content);
    post.setRecentRePostDate(rePost.getCreated());
    post.addRePostCount();  
    postService.update(post,null, null);
    rePostService.add(rePost,datas);


    return "redirect:/community/"+postID;
}
项目:forweaver2.0    文件:PostController.java   
@RequestMapping(value="/{postID}/{rePostID}/update", method = RequestMethod.POST)
public String update(@PathVariable("postID") int postID, @PathVariable("rePostID") int rePostID,HttpServletRequest request,Model model) throws UnsupportedEncodingException {       

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = multiRequest.getFileMap();
    ArrayList<Data> datas = new ArrayList<Data>();
    Post post = postService.get(postID);
    RePost rePost = rePostService.get(rePostID);
    String content = request.getParameter("content");
    Weaver weaver = weaverService.getCurrentWeaver();
    String remove = request.getParameter("remove");

    if(post == null || rePost == null || content.length() < 5 ||
            rePost.getOriginalPost().getPostID() != post.getPostID()){ // 태그가 없을 때
        model.addAttribute("say", "잘못 입력하셨습니다!!!");
        model.addAttribute("url", "/community/"+postID);
        return "/alert";
    }   

    if(!rePost.getWriter().equals(weaver) &&
            !tagService.validateTag(post.getTags(),weaver)){ // 태그에 권한이 없을때
        model.addAttribute("say", "권한이 없습니다!!!");
        model.addAttribute("url", "/community/"+postID);
        return "/alert";
    }   

    for (MultipartFile file : files.values())
        if(!file.isEmpty()){
            String fileID= dataService.getObjectID(file.getOriginalFilename(), weaver);
            if(!fileID.equals(""))
                datas.add(new Data(fileID,file,weaver));
        }

    rePost.setContent(content);
    rePostService.update(rePost,datas,remove.split("@"));

    return "redirect:/community/"+postID;   
}
项目:TITAN    文件:FileController.java   
/**
 * 压测文件上传
 * 
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/fileUpload")
@ResponseBody
public ComponentResult<FileUploadBO> fileUpload(HttpServletRequest request,HttpServletResponse response) {
    ComponentResult<FileUploadBO> componentResult = new ComponentResult<FileUploadBO>();
    //1、获取上传参数
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iterator = multiRequest.getFileNames();
        while (iterator.hasNext()) {
            MultipartFile file = multiRequest.getFile(iterator.next().toString());
            if (null != file) {
                //2、上传
                String filename = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + ".xls";
                try {
                    File targetFile = new File(pressureDataFilepath + filename);
                    file.transferTo(targetFile);
                    //3、将本地文件上传到FTP
                    boolean uploadResult = ftpUtils.uploadFile(targetFile);
                    if(uploadResult){
                        componentResult.setData(new FileUploadBO(filename));
                        return ResultUtil.success(componentResult);
                    }else{
                        logger.error("文件上传FTP失败,filename:{}",filename);
                        return ResultUtil.fail(ErrorCode.FAIL,"文件上传FTP失败",componentResult);
                    }
                } catch (IllegalStateException | IOException e) {
                    logger.error("上传文件异常,filename->" + filename,e);
                } 
            }else{
                logger.error("压测文件上传,file为NULL");
            }
        }
    }else{
        logger.error("压测文件上传,request校验失败");
    }
    //3、返回
    return ResultUtil.fail(componentResult);
}
项目:automat    文件:UploadUtil.java   
/** 上传文件处理(支持批量) */
public static List<String> uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    List<String> fileNames = InstanceUtil.newArrayList();
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        String pathDir = getUploadDir(request);
        File dirFile = new File(pathDir);
        if (!dirFile.isDirectory()) {
            dirFile.mkdirs();
        }
        for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
            String key = iterator.next();
            MultipartFile multipartFile = multiRequest.getFile(key);
            if (multipartFile != null) {
                String name = multipartFile.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                String postFix = name.substring(name.lastIndexOf(".")).toLowerCase();
                String fileName = uuid + postFix;
                String filePath = pathDir + File.separator + fileName;
                File file = new File(filePath);
                file.setWritable(true, false);
                try {
                    multipartFile.transferTo(file);
                    fileNames.add(fileName);
                } catch (Exception e) {
                    logger.error(name + "保存失败", e);
                }
            }
        }
    }
    return fileNames;
}
项目:EasyHousing    文件:UserController.java   
@RequestMapping(value="changePhoto.do", method={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public ModelAndView changePhoto(HttpServletRequest request) throws IllegalStateException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("/MyHome/userCenter");
    HttpSession s = request.getSession();
    User user = (User) s.getAttribute("user");

    // 得到文件
    String path = request.getSession().getServletContext().getRealPath("upload");  
    MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
    Iterator iter=multiRequest.getFileNames(); 
    MultipartFile file=multiRequest.getFile(iter.next().toString()); 
       String fileName = file.getOriginalFilename();    
       File dir = new File(path,fileName);          
       if(!dir.exists()){  
        dir.mkdirs();  
       }  
       //MultipartFile自带的解析方法  
       file.transferTo(dir); 

       try {
        String filePath = path + "\\" + fileName;
        System.err.println(filePath);
        String name = new Date().toInstant().toString();
        new Tool().upload(filePath, name);
        user.setUserPhoto(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
        userService.updateUser(user);
       } catch (Exception e) {
        modelAndView.addObject("infoMessage", "上传头像失败TAT");
        return modelAndView;
       }
       modelAndView.addObject("infoMessage", "上传头像成功!");
    return modelAndView;
}
项目:EasyHousing    文件:adminAgentController.java   
@RequestMapping(value="adminAddAgent.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView adminAddAgent(HttpServletRequest request, Agent agent) {
    ModelAndView modelAndView = new ModelAndView();
    HttpSession session = request.getSession();
    agent.setPicUrl("http://os8z6i0zb.bkt.clouddn.com/defaultPhoto.png"); //设置默认头像

    //插入用户上传的图片链接地址
    try {
        // 得到文件
        String path = request.getSession().getServletContext().getRealPath("upload");
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator iter = multiRequest.getFileNames();
        MultipartFile file = multiRequest.getFile(iter.next().toString());
        String fileName = file.getOriginalFilename();
        File dir = new File(path, fileName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // MultipartFile自带的解析方法
        file.transferTo(dir);

        String filePath = path + "\\" + fileName;
        System.err.println(filePath);
        String name = new Date().toInstant().toString();
        new Tool().upload(filePath, name);
        agent.setPicUrl(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
    } catch (Exception e) {

    }

    agentDao.insertAgent(agent);  //插入数据

    //更新显示层的经纪人列表
    List<Agent> agentList = agentDao.selectAll();
    session.setAttribute("agentList", agentList);

    modelAndView.setViewName("SystemUser/managerAgent");
    return modelAndView;
}
项目:lemon    文件:MultipartHandler.java   
public void handle(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        logger.debug("force cast to MultipartHttpServletRequest");

        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        this.multiFileMap = req.getMultiFileMap();
        logger.debug("multiFileMap : {}", multiFileMap);
        this.handleMultiValueMap(req);
        logger.debug("multiValueMap : {}", multiValueMap);

        return;
    }

    if (multipartResolver.isMultipart(request)) {
        logger.debug("is multipart : {}",
                multipartResolver.isMultipart(request));
        this.multipartHttpServletRequest = multipartResolver
                .resolveMultipart(request);

        logger.debug("multipartHttpServletRequest : {}",
                multipartHttpServletRequest);
        this.multiFileMap = multipartHttpServletRequest.getMultiFileMap();
        logger.debug("multiFileMap : {}", multiFileMap);
        this.handleMultiValueMap(multipartHttpServletRequest);
        logger.debug("multiValueMap : {}", multiValueMap);
    } else {
        this.handleMultiValueMap(request);
        logger.debug("multiValueMap : {}", multiValueMap);
    }
}
项目:logistimo-web-service    文件:FileUploadServlet.java   
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (!isMultipart) {
    return;
  }
  try {
    MultipartHttpServletRequest
        multiRequest =
        new CommonsMultipartResolver().resolveMultipart(request);
    MultiValueMap<String, MultipartFile> fileMap = multiRequest.getMultiFileMap();
    BlobstoreService blobstoreService = AppFactory.get().getBlobstoreService();
    Map<String, String> names = new HashMap<>(1);
    for (String fieldName : fileMap.keySet()) {
      MultipartFile file = fileMap.getFirst(fieldName);
      String fileName = file.getOriginalFilename();
      String contentType = file.getContentType();
      long sizeInBytes = file.getSize();
      String
          blobKey =
          blobstoreService.store(fileName, contentType, sizeInBytes, file.getInputStream());
      names.put(fieldName, blobKey);

    }
    request.getSession().setAttribute("blobs", names);
    RequestDispatcher
        dispatcher =
        getServletContext().getRequestDispatcher(request.getParameter("ru"));
    dispatcher.forward(multiRequest, response);
  } catch (Exception ex) {
    _logger.severe("Upload failed", ex);
  }
}
项目:logistimo-web-service    文件:DirectFileUploadServlet.java   
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (!isMultipart) {
    return;
  }
  try {
    MultipartHttpServletRequest
        multiRequest =
        new CommonsMultipartResolver().resolveMultipart(request);
    MultiValueMap<String, MultipartFile> fileMap = multiRequest.getMultiFileMap();
    BlobstoreService blobstoreService = AppFactory.get().getBlobstoreService();
    Map<String, String> names = new HashMap<>(1);
    for (String fieldName : fileMap.keySet()) {
      MultipartFile file = fileMap.getFirst(fieldName);
      String fileName = file.getOriginalFilename();
      String contentType = file.getContentType();
      long sizeInBytes = file.getSize();
      String
          blobKey =
          blobstoreService.store(fileName, contentType, sizeInBytes, file.getInputStream());
      names.put(fieldName, blobKey);
      names.put("file", fileName);

    }
    response.getWriter().write(new Gson().toJson(names));
    response.setStatus(HttpStatus.SC_CREATED);
  } catch (Exception ex) {
    _logger.severe("Upload failed", ex);
  }
}
项目:mumu    文件:DocUploadController.java   
/**
 * 上传文件
 * @param request
 * @return
 */
public File uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    try {
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iterator = multiRequest.getFileNames();
            while (iterator.hasNext()) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String name = multipartFile.getOriginalFilename();
                    String pathDir = request.getSession().getServletContext().getRealPath("/upload/" + DateUtils.currentTime());
                    File dirFile = new File(pathDir);
                    if (!dirFile.isDirectory()) {
                        dirFile.mkdirs();
                    }
                    String filePath = pathDir+File.separator+name;
                    File file = new File(filePath);
                    file.setWritable(true, false);

                    multipartFile.transferTo(file);
                    return file;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}