基于JSP自定义Ueditor 上传 aliyun OSS

步骤如下

下载官方源码

依赖:jsp/lib,aliyun-openservices-1.2.3.jar,下载你懂的…………

概述

ueditor 所有上传的通过统一入口是ActionEnter,然后根据ActionEnter处理,调用对应存储器实现文件上传。

实现

  • 入口
/* ActionEnter部分源码 */
// 核心方法
public String invoke() {
	if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
		return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
	}
	if ( this.configManager == null || !this.configManager.valid() ) {
		return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
	}
	
	State state = null;
	
	int actionCode = ActionMap.getType( this.actionType );
	
	Map<String, Object> conf = null;
	
	switch ( actionCode ) {
		// 编辑器初始化,获取所有配置参数信息        
		case ActionMap.CONFIG:
			return this.configManager.getAllConfig().toString();
		// 文件上传
		case ActionMap.UPLOAD_IMAGE:
		case ActionMap.UPLOAD_SCRAWL:
		case ActionMap.UPLOAD_VIDEO:
		case ActionMap.UPLOAD_FILE:
			conf = this.configManager.getConfig( actionCode );
			// 通过上传器,执行上传
			state = new Uploader( request, conf ).doExec();
			break;
		// 抓取远程图片
		case ActionMap.CATCH_IMAGE:
			conf = configManager.getConfig( actionCode );
			String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
			// 调用抓取器
			state = new ImageHunter( conf ).capture( list );
			break;
		// 获取文件列表	
		case ActionMap.LIST_IMAGE:
		case ActionMap.LIST_FILE:
			conf = configManager.getConfig( actionCode );
			int start = this.getStartIndex();
			state = new FileManager( conf ).listFile( start );
			break;
			
	}
	
	return state.toJSONString();
	
}
  • 上传器
public class Uploader {
	private HttpServletRequest request = null;
	private Map<String, Object> conf = null;

	public Uploader(HttpServletRequest request, Map<String, Object> conf) {
		this.request = request;
		this.conf = conf;
	}

	public final State doExec() {
		String filedName = (String) this.conf.get("fieldName");
		State state = null;
                // Base64 编码 主要是涂鸦的时候调用
		if ("true".equals(this.conf.get("isBase64"))) {
			state = Base64Uploader.save(this.request.getParameter(filedName),
					this.conf);
		} else {
                        // 非Base64 编码调用
			state = BinaryUploader.save(this.request, this.conf);
		}
		return state;
	}
}
  • 文件上传保存(OSS上传)
/* BinaryUploader.class 部分源码  */
String savePath = (String) conf.get("savePath");
String originFileName = fileStream.getName();
String suffix = FileType.getSuffixByFilename(originFileName);

originFileName = originFileName.substring(0,originFileName.length() - suffix.length());
savePath = savePath + suffix;

long maxSize = ((Long) conf.get("maxSize")).longValue();

if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
	return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}

savePath = PathFormat.parse(savePath, originFileName);
// 绝对路径,我注释调,没有用,详见StorageManager.saveFileByInputStream
// String physicalPath = (String) conf.get("rootPath") + savePath;

InputStream is = fileStream.openStream();
// 我传savePath,作为OSS目录
State storageState = StorageManager.saveFileByInputStream(is, savePath , maxSize);

/* 基于StorageManager.class 实现上传,部分源码*/
	public static State saveFileByInputStream(InputStream is, String path, long maxSize) {
        State state = null;

        // 创建临时文件
        File tmpFile = getTmpFile();

        byte[] dataBuf = new byte[2048];
        BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();

            // 上传文件大小限制
            if (tmpFile.length() > maxSize) {
                tmpFile.delete();
                return new BaseState(false, AppInfo.MAX_SIZE);
            }

            try {
                // endpoint 阿里云OSS地址
                String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
                // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建
                String accessKeyId = "<yourAccessKeyId>";
                String accessKeySecret = "<yourAccessKeySecret>";

                // 创建OSSClient实例
                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                InputStream inputStream = new FileInputStream(tmpFile);

                // 使用aliyunopenservices 包(maven 远程仓库中)
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(tmpFile.length());

                // path.substring(1) 我去掉路径第一个/ 不然OSS创建不了
                ossClient.putObject("<yourBucketName>", path.substring(1), inputStream, objectMetadata);

                // 注:返回必须遵守Sate 返回
                state = new BaseState(true, "上传阿里OSS成功");
            } catch (Exception ex) {
                ex.printStackTrace();
                state = new BaseState(false, "上传阿里OSS失败");
            }


	  /*去掉原生文件复制
            state = saveTmpFile(tmpFile, path);
          */
           tmpFile.delete();

            return state;

        } catch (IOException e) {
        }
        return new BaseState(false, AppInfo.IO_ERROR);
    }

OK,这样子就可以,若有其他需求,重构一下源码,即可。

转载于:https://my.oschina.net/uRick/blog/1790693

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值