1. 程式人生 > >關於富文字編輯器ueditor(jsp版)上傳檔案到阿里雲OSS的簡單例項,適合新手

關於富文字編輯器ueditor(jsp版)上傳檔案到阿里雲OSS的簡單例項,適合新手

       本人菜鳥一枚,最近公司有需求要用到富文字編輯器,我選擇的是百度的ueditor富文字編輯器,閒話不多說,進入正題:
一:ueditor的下載及安裝以及OSS的下載及引入我就不詳細說了,這裡說下要注意的幾點:  
     1,ueditor下載地址:點選開啟連結,記得下載的是開發版 - 完整原始碼版
     2,oss -java-sdk下載地址:點選開啟連結
     3,至於ueditor安裝及初始化方法,自行百度.OSS引入包放如專案lib資料夾即可開始使用

     4,此例項只是增加UploadOSSUtil.java及修改BinaryUploader.java即可,其他地方不用做任何修改


二:安裝完成後需要更改的地方:       
     1,開啟包com.baidu.ueditor.upload,新建class檔案: UploadOSSUtil.java內容如下

package com.baidu.ueditor.upload;


/**
 * 上傳到阿里雲:xhj
 * 
 * 
 */
import java.io.FileNotFoundException;
import java.io.InputStream; 
import com.aliyun.oss.OSSClient; 


public class UploadOSSUtil {
	public UploadOSSUtil(){}
	
	public static void uploadImgAliyun(InputStream inputStream ,String fileName)
	throws FileNotFoundException{
		String accesskeyId = "***你的阿里雲accesskeyId***" ;  
		String accessKeySecret = "***你的阿里雲accessKeySecret***" ;  
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com" ;  
		String bucketName = "***你的bucketName***" ;  
		OSSClient client = new OSSClient(endpoint,accesskeyId,accessKeySecret);  
		//此處"images/companyNewsImages/"+fileName,表示上傳至阿里雲中images資料夾下的companyNewsImages資料夾中,請修改為自己的路徑即可  
		client.putObject(bucketName, "images/companyNewsImages/"+fileName, inputStream);  
		client.shutdown();
	}
}


修改同目錄下的BinaryUploader.java的save()

public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;


		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}


		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());


        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }


		try {
			FileItemIterator iterator = upload.getItemIterator(request);


			while (iterator.hasNext()) {
				fileStream = iterator.next();


				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}


			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}


			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);


			String physicalPath = (String) conf.get("rootPath") + savePath;
			
			InputStream is = fileStream.openStream();
			
			/**
			 * 上傳到阿里雲:xhj新增
			 */
			//*******************開始***********************
			String fileName = new StringBuffer().append(new Date().getTime()).append(fileStream.getName().substring(fileStream.getName().indexOf("."))).toString();
			State storageState = null;
			try {
				
				new UploadOSSUtil();
				UploadOSSUtil.uploadImgAliyun(is,fileName);
				storageState = StorageManager.saveFileByInputStream(is,
						physicalPath, maxSize);
				storageState.putInfo("state", "SUCCESS");
				//url:返回前端的訪問路徑,請根據自己實際情況填寫
				storageState.putInfo("url","http://kbs-test.oss-cn-shenzhen.aliyuncs.com/images/companyNewsImages/" + fileName);
				storageState.putInfo("title", fileName);
				storageState.putInfo("original", fileName);
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println(e.getMessage());
				storageState.putInfo("state", "檔案上傳失敗!");
				storageState.putInfo("url","");
				storageState.putInfo("title", "");
				storageState.putInfo("original", "");
	            //System.out.println("檔案 "+fileName+" 上傳失敗!");
			}
			
			
			
			//********************結束**********************
			
			is.close();
			/*if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}*/
			//System.out.println("storageState="+storageState);
			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}



如有疑問,歡迎提問。

PS:抽點時間做了個Demo,親測可用

1:連結:https://pan.baidu.com/s/16C_ww0hFJPLkYJoBU8iyAQ      密碼:eq5u

2:https://download.csdn.net/download/u013189988/10450304

以上兩個地址都是相同的原始碼,請自行下載。轉載請註明出處,謝謝!