spring上传文件(request未被CommonsMultipartResolver处理)

/**
	 * @Description: 
	 * @param request
	 * @param nameParam:要获取的表单的file名
	 * @Return: String
	 */
	public static HashMap<String,Object> uploadFileWidthLimit(HttpServletRequest request, String nameParam){
		
		String fileUrl = "";
		boolean isFail= false;
		String errMsg = "";
		try{
			//获取上传文件的类型img,flash,file
			String type = request.getParameter("type");
			CommonsMultipartResolver commonsMultipartResolver = 
					new CommonsMultipartResolver(request.getSession().getServletContext());
			//根据type类型获取限制上传的大小,单位字节
			long limit = UtilConfig.getLong(type+".limit", 1024*1024);
			commonsMultipartResolver.setMaxUploadSize(limit);
			MultipartHttpServletRequest multipartRequest =  commonsMultipartResolver.resolveMultipart(request);
			
			//文件存储路径
			String currentPath = Constants.NEWS_UPLOADPATH+"/"+type;
			String currentDirPath = request.getServletContext().getRealPath(currentPath);
			// 将路径前加上web应用名
			currentPath = request.getContextPath()+"/" + currentPath;
			
			logger.debug("currentPath>>>>>>{}",currentPath);
			logger.debug("currentDirPath>>>{}",currentDirPath);
			
			
			MultipartFile file = multipartRequest.getFile(nameParam);
				String fileName = file.getOriginalFilename();
				logger.debug("fileName>>>>{}",fileName);
				// 获取文件扩展名
				String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
				//检测扩展名是否合法
				ArrayList allowList = (ArrayList) allowedExtensions.get(type);
				if(allowList.contains(ext)){
					fileName = UtilDate.formatDateTime2()
							+ RandomStringUtil.getRandomNum(3)
							+ fileName.substring(fileName.lastIndexOf("."));
					File pathToSave = new File(currentDirPath,fileName);
					if(!pathToSave.exists())
						pathToSave.mkdirs();
					fileUrl = currentPath + "/" + fileName;
					file.transferTo(pathToSave);
				}else {
					isFail = true;
					errMsg="无效的文件类型: ";
				}
		}catch(Exception ex){
			ex.printStackTrace();
			isFail = true;
			errMsg="未知错误!";
		}
		HashMap<String,Object> map = new HashMap();
		map.put("isFail", isFail);
		map.put("errMsg", errMsg);
		map.put("fileUrl", fileUrl);
		logger.debug("isFail>>>{}",isFail);
		logger.debug("errMsg>>>>{}",errMsg);
		logger.debug("fileUrl>>>{}",fileUrl);
		return map;
	}

 

你可能感兴趣的:(spring上传文件(request未被CommonsMultipartResolver处理))