1. 程式人生 > >使用阿里雲OSS伺服器進行web簽名直傳

使用阿里雲OSS伺服器進行web簽名直傳

@Controller
@RequestMapping("oss")
public class OssUploadController {
	private static Logger log = LoggerFactory.getLogger(OssUtils.class);
	
	/**
	 * 獲取oss簽名
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getSign")
	public void getOssSign(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/plain;charset=UTF-8");
		Enumeration<String> keyList = request.getParameterNames();
		Map<String, String> paramMap = new HashMap<String, String>();
		while(keyList.hasMoreElements()) {
			String key = keyList.nextElement();
			paramMap.put(key, request.getParameter(key));
		}
		RiskCookieDto dto = RiskCookiesUtils.getUserInfoDefault(request);
		paramMap.put("userCode", dto.getUserCode());
		String callback = paramMap.remove("callback");
		PrintWriter out = response.getWriter();
		log.info("回撥地址:" + callback);
		log.info("回撥引數:" + paramMap);
		out.write(OssUtils.getOssSign(callback, paramMap).toString());
		out.flush();
		out.close();
	}
	
	@RequestMapping("callback")
	public void callBack(HttpServletRequest request) {
		String key = request.getParameter("key");
		InputStream is = OssUtils.getOssFileSteam(key);
		try {
			if (is != null) {
			    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			    while (true) {
			        String line = reader.readLine();
			        if (line == null) break;
			        log.info("\n" + line);
			    }
			    is.close();
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}
}
前段js需要下載plupload外掛https://help.aliyun.com/document_detail/31927.html?spm=5176.doc32009.6.630.Nr4UNj下載及使用的地址
var uploader = null,//上傳器
accessid = '',//Id
host = '',//主機
policyBase64 = '',//policy
signature = '',//簽名
callbackbody = '',//回撥內容
expire = 0,//過期時間
g_object_name_type = '',//型別檢測
now = Date.parse(new Date()) / 1000,//當前時間
isSign = false,	//簽名狀態
basePathUrl = window.location.protocol + "//" + window.location.host + "/finance";//獲取當前請求地址

var isFirst = true;

var ossParams = {
	callbackParams : {},//回撥傳遞的引數
	filekeyValues : {}, //檔名與上傳儲存的檔案對應集合key為檔名value為上傳儲存的檔名
	mimeTypes : [],//上傳檔案格式設定
	init : ossUploadInitAction,//上傳初始化的操作函式
	added : ossUploadAddedAction,//上傳新增檔案後的操作函式
	before : ossBeforeUploadAction,//上傳之前的操作函式
	progress : ossUploadProgressAction,//上傳過程中的操作函式
	after : ossAfterUploadAction,//上傳之後的操作函式
	error : ossUploadErrorAction//上傳失敗的操作函式
}

/**
 * 初始化oss引數
 * 
 * @author zhy
 * @param param 引數json
 */
function initParams(param) {
	if(param["callbackParams"]) {
		ossParams["callbackParams"] = param["callbackParams"]
	}
	
	if(param["mimeTypes"]) {
		ossParams["mimeTypes"] = param["mimeTypes"]
	}
	
	if(param["init"]) {
		ossParams["init"] = param["init"]
	}
	
	if(param["added"]) {
		ossParams["added"] = param["added"]
	}
	
	if(param["before"]) {
		ossParams["before"] = param["before"]
	}
	
	if(param["progress"]) {
		ossParams["progress"] = param["progress"]
	}
	
	if(param["after"]) {
		ossParams["after"] = param["after"]
	}
	
	if(param["error"]) {
		ossParams["error"] = param["error"]
	}
}

/**
 * 初始化上傳外掛
 * 
 * @author zhy
 * @param selectfilesId 選擇檔案物件ID
 */
function ossUploadInit(selectfilesId, param) {
	initParams(param);
	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : selectfilesId,
//	    multi_selection: false,
		container: document.getElementById('container'),
		flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',

	    filters: {
	        mime_types : ossParams['mimeTypes'],
	        max_file_size : '10mb', //最大隻能上傳10mb的檔案
	        prevent_duplicates : true //不允許選取重複檔案
	    },
	
		init: {
			PostInit: function() {
				ossParams['init']()
			},
			FilesAdded: function(up, files) {
				isFirst = true;
				ossParams['added'](up, files)
			},
			BeforeUpload: function(up, file) {
				get_signature();
				ossParams['before'](up, file)
			},
			UploadProgress: function(up, file) {
				ossParams['progress'](up, file)
			},
			FileUploaded: function(up, file, info) {
				ossParams['after'](up, file, info)
				uploader.refresh();
			},
			Error: function(up, error) {
				ossParams['error'](up, error)
				uploader.refresh();
			}
		}
	})
	
	uploader.init();
}

/**
 * 開始上傳
 * 
 * @author zhy
 */
function ossStartUpload() {
	if(filekeyValues[uploader.files[0].name] && isFirst == false) {
		window.wxc.xcConfirm("不能連續上傳同一個檔案!", window.wxc.xcConfirm.typeEnum.error);
		myTipsHiden();
	} else {
		isFirst = false;
		uploader.start();
	}
}

/**
 * 獲取服務端簽名
 * 
 * @author zhy
 * @returns {Boolean}
 */
function get_signature() {
	// 可以判斷當前expire是否超過了當前時間,如果超過了當前時間,就重新取一下.3s 做為緩衝
	now = timestamp = Date.parse(new Date()) / 1000;
	if (expire < now + 3) {
		serverUrl = basePathUrl + '/oss/getSign';
	    $.ajax({
	      type:'post',
	      url:serverUrl,
	      data:ossParams["callbackParams"],
	      dataType:'json',
	      async : false,
	      success:function(result) {
	    	  host = result['host']
	    	  policyBase64 = result['policy']
	    	  accessid = result['accessid']
	    	  signature = result['signature']
	    	  expire = parseInt(result['expire'])
	    	  callbackbody = result['callback']
	      }
		});
		return true;
	}
	return false;
};

/**
 * 獲取字尾名
 * 
 * @author zhy
 * @param filename 檔名
 * @returns {String}
 */
function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function check_object_radio() {
	var tt = document.getElementsByName('myradio');
	for (var i = 0; i < tt.length; i++) {
		if (tt[i].checked) {
			g_object_name_type = tt[i].value;
			break;
		}
	}
}

function ossUploadInitAction() {
	console.info('上傳初始化操作函式');
}

function ossUploadAddedAction(up, files) {
	console.info("新增的操作函式")
}

function ossBeforeUploadAction(up, file) {
	console.info("上傳之前的操作函式")
	check_object_radio();
	new_multipart_params = {
        'key' : ossParams["filekeyValues"][file.name],
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //讓服務端返回200,不然,預設會返回204
        'callback' : callbackbody,
        'signature': signature,
    };
	up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
}

function ossUploadProgressAction(up, file) {
	console.info("上傳過程中的操作函式");
}

function ossAfterUploadAction(up, file, info) {
	if (info.status == 200)
    {
        console.info('upload to oss success, object name:' + file.name + ' 回撥伺服器返回的內容是:' + info.response);
    }
    else if (info.status == 203)
    {
        console.info('上傳到OSS成功,但是oss訪問使用者設定的上傳回調伺服器失敗,失敗原因是:' + info.response);
    }
    else
    {
        console.info(info.response);
    } 
}

function ossUploadErrorAction(up, err) {
	console.info("上傳出錯的操作函式")
	if (err.code == -600) {
        console.error("\n選擇的檔案太大了,可以根據應用情況,在upload.js 設定一下上傳的最大大小");
    }
    else if (err.code == -601) {
        console.error("\n選擇的檔案字尾不對,可以根據應用情況,在upload.js進行設定可允許的上傳檔案型別");
    }
    else if (err.code == -602) {
        console.error("\n這個檔案已經上傳過一遍了");
    }
    else 
    {
        console.error("\nError xml:" + err.response);
    }
}