`
lihao312
  • 浏览: 483914 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

记录springmvc+ueditor1.4.3上传附件问题

阅读更多
百度富文本编辑器地址:http://ueditor.baidu.com/website/index.html

1.UEditor上传目录



2.在ueditor.config.js中配置serverUrl: "/resources/plugin/ueditor"

3.后台配置访问路径
@RequestMapping("resources/plugin/ueditor")
	public void baiduEdit(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html");
			
			String rootPath = request.getServletContext().getRealPath("/");
			logger.debug("================>{}", rootPath);
			//针对配置百度上传附件读取配置文件
			ActionMap.mapping.put("config", ActionMap.CONFIG);
			//上传文件
			ActionMap.mapping.put("uploadfile", ActionMap.UPLOAD_FILE);
			ActionEnter actionEnter = new ActionEnter(request, rootPath);
			response.getWriter().write(actionEnter.exec());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

配置成功后,可以启动项目, 执行url
http://localhost:8080/longchoudai/resources/plugin/ueditor?action=config
可以看到你配在config.json中的Json数据

4.上传附件时候修改原百度BinaryUploader.java 在目录com.baidu.ueditor.upload下面
public class BinaryUploader {
	private static Logger logger = LogManager.getLogger();
	
	/**
	 * 保存文件
	 * @author lance
	 * 2015年8月27日 下午2:26:49
	 */
	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, 5);
		}
		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());
		if (isAjaxUpload) {
			upload.setHeaderEncoding("UTF-8");
		}
		try {
			String savePath = request.getServletContext().getRealPath("/")+"/attached/file/"+JodaTimeUtils.dateToString(new Date(), null)+"/";
			String saveUrl  = request.getContextPath() + "/attached/file/";
			
			//上传附件目录
			Path path = Paths.get(savePath);
			if(!Files.isDirectory(path)){
				try {
					Files.createDirectories(path);
				} catch (IOException e) {
					logger.error("百度上传附件创建上传文件夹错误: {}", e.getMessage());
				}
			}
	        //重新命名文件名字
			String newFileName = "", fileExt = "", fileName = "";
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)) {
				//将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	            //获取multiRequest 中所有的文件名
	            Iterator<String>it=multiRequest.getFileNames();
	            //遍历文件
	            while(it.hasNext()) {
	            	MultipartFile file=multiRequest.getFile(it.next().toString());
	            	if(file != null){
	            		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	            		fileName = file.getOriginalFilename();
	            		fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
	            		//新文件名称
						newFileName = savePath + df.format(new Date()) + "_" + new Random().nextInt(1000) + fileExt;
						saveUrl = saveUrl + df.format(new Date()) + "_" + new Random().nextInt(1000) + fileExt;
						if (!validType(fileExt, (String[])conf.get("allowFiles"))) {
					        return new BaseState(false, 8);
					      }
						try {
							//上传文件
							file.transferTo(new File(newFileName));
						} catch (IllegalStateException | IOException e) {
							logger.error("百度上传附件保存文件错误: {}", e.getMessage());
						}
	            	}
	            }
			}
			
	        State storageState = new BaseState(Boolean.TRUE);
			if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(saveUrl));
				storageState.putInfo("type", fileExt);
				storageState.putInfo("original", fileName);
			}
			return storageState;
		} catch (Exception e) {
			logger.error("百度上传附件文件错误: {}", e.getMessage());
		}
		return new BaseState(false, 4);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);
		return list.contains(type);
	}
}




  • 大小: 29.2 KB
  • 大小: 46.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics