当前位置: 首页>>代码示例>>Java>>正文


Java MultipartHttpServletRequest.getFile方法代码示例

本文整理汇总了Java中org.springframework.web.multipart.MultipartHttpServletRequest.getFile方法的典型用法代码示例。如果您正苦于以下问题:Java MultipartHttpServletRequest.getFile方法的具体用法?Java MultipartHttpServletRequest.getFile怎么用?Java MultipartHttpServletRequest.getFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.web.multipart.MultipartHttpServletRequest的用法示例。


在下文中一共展示了MultipartHttpServletRequest.getFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: add

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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/";
}
 
开发者ID:forweaver,项目名称:forweaver2.0,代码行数:26,代码来源:CodeController.java

示例2: updateLogo

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:26,代码来源:MarketAppServiceImpl.java

示例3: updateIndexImg

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:27,代码来源:AppServiceImpl.java

示例4: uploadFile

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
 * 上传文件
 * @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;
}
 
开发者ID:babymm,项目名称:mmsns,代码行数:36,代码来源:DocUploadController.java

示例5: updateIndexImg

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
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);
    }
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:27,代码来源:MarketAppServiceImpl.java

示例6: upload

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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();
}
 
开发者ID:nickevin,项目名称:Qihua,代码行数:27,代码来源:ProductImgController.java

示例7: uploadRecommend

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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();
}
 
开发者ID:nickevin,项目名称:Qihua,代码行数:27,代码来源:ProductImgController.java

示例8: uploadCenter

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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();
}
 
开发者ID:nickevin,项目名称:Qihua,代码行数:26,代码来源:HomeController.java

示例9: doUploadImageAjax

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
 * Upload an image using AJAX. The response will be returned as JSON object.
 *
 * @param request
 *            the servlet request
 * @param userId
 *            the ID of the user whose image will be updated
 * @return the JSON response object
 */
private ObjectNode doUploadImageAjax(HttpServletRequest request, Long userId) {

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
    String errorMessage = null;
    if (cFile != null && cFile.getSize() > 0) {
        if (cFile.getSize() < getMaxUploadSize()) {
            errorMessage = storeImage(request, cFile, userId);
        } else {
            errorMessage = MessageHelper.getText(request, "user.profile.upload.filesize.error",
                    new Object[] { FileUtils.byteCountToDisplaySize(getMaxUploadSize()) });
        }
    } else {
        errorMessage = MessageHelper.getText(request, "user.profile.upload.empty.image");
    }
    if (errorMessage != null) {
        return JsonRequestHelper.createJsonErrorResponse(errorMessage);
    }
    return JsonRequestHelper.createJsonSuccessResponse(null, createSuccessResult(userId));
}
 
开发者ID:Communote,项目名称:communote-server,代码行数:30,代码来源:UserProfileActionController.java

示例10: saveImage

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
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;
}
 
开发者ID:puyangsky,项目名称:GeneralCompanyProject,代码行数:19,代码来源:UserService.java

示例11: uploadFile

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/** 上传文件处理(支持批量) */
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;
}
 
开发者ID:guokezheng,项目名称:automat,代码行数:35,代码来源:UploadUtil.java

示例12: updateLogo

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
public void updateLogo(MultipartHttpServletRequest multipartReq, App app) throws IOException,
        MalformedURLException, URISyntaxException {
    int id = app.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.saveFile(id, file);
    } else if (StringUtils.isNotBlank(remoteLogoUrl)) {
        // 拉取图片.
        logoSubPath = attachmentService.saveFile(id, remoteLogoUrl);
    }
    if (StringUtils.isNotBlank(logoSubPath)) {
        String logoUrl = PathUtils.concate(appConfig.getDestUploadBaseurl(), logoSubPath);
        app.setLogoUrl(logoUrl);
        saveOrUpdate(app);
        needToDeleteLogoUrlBak = true;
    }
    if (StringUtils.isNotBlank(logoUrlBak) && needToDeleteLogoUrlBak) {
        attachmentService.deleteFile(logoUrlBak);
    }

    appHistory4IndexDao.saveOrUpdate(app.getId());
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:28,代码来源:AppServiceImpl.java

示例13: changePhoto

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:632team,项目名称:EasyHousing,代码行数:36,代码来源:UserController.java

示例14: adminAddAgent

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
@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;
}
 
开发者ID:632team,项目名称:EasyHousing,代码行数:40,代码来源:adminAgentController.java

示例15: uploadFile

import org.springframework.web.multipart.MultipartHttpServletRequest; //导入方法依赖的package包/类
/**
    * 上传文件处理(支持批量)
    * @param request
    * @param pathDir 上传文件保存路径
    * @return
    * @throws IllegalStateException
    * @throws IOException
    */
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = InstanceUtil.newArrayList();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		if(pathDir==null|| pathDir.equals("")){
			pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
		}
           File dirFile = new File(pathDir);
           if (!dirFile.isDirectory()) {
               dirFile.mkdirs();
           }
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String uuid = UUID.randomUUID().toString().replace("-", "");
				String name = multipartFile.getOriginalFilename();
				int lastIndexOf = name.lastIndexOf(".");
				String postFix="";
				if(lastIndexOf!=-1){
					postFix = name.substring(lastIndexOf).toLowerCase();
				}
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}
 
开发者ID:babymm,项目名称:mumu,代码行数:46,代码来源:UploadUtil.java


注:本文中的org.springframework.web.multipart.MultipartHttpServletRequest.getFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。