1. 程式人生 > >阿里雲oss js前端獲取簽名直傳檔案

阿里雲oss js前端獲取簽名直傳檔案

1. 原來的官方文件是先選擇檔案,再點選上傳按鈕,上傳檔案,我這裡是選擇完檔案,就上傳,這裡主要是在FilesAdded這個裡面新增完檔案,立刻初始化一次set_upload_param(uploader, '', true); 就能選擇完就上傳了.

2.這個只是個簡單的圖片上傳,沒有用到<input>這個屬性來選擇檔案,,好像用  plupload  裡面的屬性  browse_button  來選擇檔案的,我同事用其他外掛來上傳檔案,

  這裡有個坑,就是你那個<input   name="file">,就是你的選擇檔案的input的name屬性必須是file,否者會出現

IncorrectNumberOfFilesInPOSTRequest 錯誤,好坑.

3. 這個地址是阿里雲原始碼來的,AppPostPolicyServer是簽名的java專案,ss-h5-upload-js-php資料夾裡面是前端直傳,具體自己下載看看或者去官方下載也可以.我就是

    根據這兩個資料夾的東西來修該出我下面的程式碼的.其他就需要你看官方文件了.

   http://download.csdn.net/download/hch15112345824/10121664

  這個是我檔案上傳的最後想要的效果圖,點選上傳圖片,選擇完圖片,直接檔案上傳到阿里雲,然後顯示URL,圖片的地方也顯示上傳的圖片.


jsp的程式碼如下:

                            <!-- 阿里雲上傳 -->
							<div id="container" class="dl-horizontal form-group">
								<a id="selectfiles" href="javascript:void(0);" class="btn btn-circle btn-success" data-style="expand-left" data-spinner-color="#333">上傳圖片</a>
								<a id="postfiles" href="javascript:void(0);"></a>
							</div>
							<!-- 這個顯示進度的 -->	
						 	<div id="ossfile"></div>																			                          
                         </div>  

js的程式碼如下:

// id.
accessid = ''
// 祕鑰.
accesskey = ''
// host: 指的是使用者要往哪個域名發往上傳請求   host+檔名就是下載路徑了.
host = ''
// policy:指的是使用者表單上傳的策略policy,是經過base64編碼過的字串.
// 加密.
policyBase64 = ''
// signature:是對上述第三個變數policy簽名後的字串.
signature = ''
// 返回的body.
callbackbody = ''
// 檔案的名字.	
filename = ''
key = ''
// 過期時間.
expire = 0
// 檔名字.
g_object_name = ''
// 檔案型別. local_name
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000; 
// 這個是獲取accessid policy signature dir host expire.
function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = ctx + '/aliyun/getPolicy';
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText;
    }
    else
    {
    	alert("您的瀏覽器不支援XMLHTTP,請換瀏覽器登入再使用.");
    }
};

function get_signature()
{
    // 可以判斷當前expire是否超過了當前時間,如果超過了當前時間,就重新取一下.3s 做為緩衝.
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

// 擷取檔案的字尾.
function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

// 上傳的時候檔案儲存路徑和名稱:我這裡是 資料夾+uuid+檔案字尾.
function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
    	var uuid = generateUUID();
        suffix = get_suffix(filename);
        g_object_name = key + uuid + suffix;
    }
    return ''
}

//初始化一些引數.
function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', // 讓服務端返回200,不然,預設會返回204.
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

// 這裡是官方原來的文件程式碼,集體如下.
var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
	container: document.getElementById('container'),
	flash_swf_url : 'static/aliyunUpload/Moxie.swf',
	silverlight_xap_url : 'static/aliyunUpload/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
	multi_selection : false,

    filters: {
        mime_types : [ // 只允許上傳圖片和zip,rar檔案.
        { title : "Image files", extensions : "jpg,gif,png,bmp" }
        ],
        max_file_size : '10mb', // 最大隻能上傳10mb的檔案.
        prevent_duplicates : true // 不允許選取重複檔案.
    },

	init: {
		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
				+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
				+'</div>';
			});
			set_upload_param(uploader, '', true);
		},

		BeforeUpload: function(up, file) {
            set_upload_param(up, file.name, false);
        },

		UploadProgress: function(up, file) {
			var d = document.getElementById(file.id);
			d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
			var progBar = prog.getElementsByTagName('div')[0]
			progBar.style.width= 2*file.percent+'px';
			progBar.setAttribute('aria-valuenow', file.percent);
		},

		FileUploaded: function(up, file, info) {
			uploader.removeFile(file);
			var imgDir = host+g_object_name;
			var title = file.name;
            if (info.status == 200) {
    			$.ajax({
    				url: ctx + '/advertisement/aliUpload',
    				type:"post",
    				async: false,
    				data:{
    					"imgDir" : imgDir,
    					"productId" : productId,
    					"title" : title
    				},
    				dataType:"json",
    				success: function (data) {
    		           	if(data.isSuccess == '1'){
    		           		$("#imgDir").val(data.imgDir);
    		           		$("#imgView").attr('src', data.imgDir);
    		           		// 刪除進度條資訊.
    		           		$("div#"+file.id).remove();
    		           	}else{
    		           		alert("儲存資訊失敗,請重新上傳檔案.");
    		           		delFileList();
    		           	}
    				},
    				error: function (data, textStatus) {
    					alert("上傳失敗,請檢查網路之後重新上傳.");
    					delFileList();
    				}
    			});
            } else {
				alert("上傳失敗,請檢查網路之後重新上傳.");
				delFileList();
            } 
		},

		Error: function(up, err) {
            if (err.code == -600) {
            	alert("選擇的檔案太大了,重新選擇檔案.");
            }
            else if (err.code == -601) {
            	alert("選擇的檔案字尾不對,重新選擇檔案.");
            }
            else if (err.code == -602) {
            	alert("這個檔案已經上傳過一遍了或者已存在上傳佇列面,請確認再上傳.");
            }
            else 
            {
            	alert("上傳出現錯誤,請稍後再試.");
            	console.log(err);
            	console.log(up);
            }
            delFileList();
		}
	}
});

// 出錯刪除上傳佇列重新上傳.
function delFileList(){
    document.getElementById('ossfile').innerHTML="";
    uploader.splice(0,9999);
}

// 獲取uuid.
function generateUUID() {
	var d = new Date().getTime();
	var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	  var r = (d + Math.random()*16)%16 | 0;
	  d = Math.floor(d/16);
	  return (c=='x' ? r : (r&0x3|0x8)).toString(16);
	});
	return uuid;
};

uploader.init();