<!doctype html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>js上傳圖片到七牛</title> <style> #container{ width:200px; height:200px; border:1px solid #9d9d9d; border-radius: 6px; margin:50px auto; position: relative; overflow: hidden; } .upload-progress{ width:100%; height:100%; position: absolute; top:0; left:0; background: rgba(0,0,0,0.5); z-index: 5; color:#fff; line-height: 200px; text-align: center; display: none; } #uploadImage{ width:100%; height:100%; position: absolute; top:0; left:0; z-index: 2; text-align: center; line-height: 200px; cursor: pointer; } #container img{ width:100%; position: absolute; top:0; left:0; z-index: 1; } </style> </head> <body> <div id="container"> <div id="uploadImage">選擇文件</div> <div class="upload-progress"></div> </div> <script src="/moxie.js"></script> <script src="/plupload.min.js"></script> <script src="/qiniu.js"></script> <script> var uploader = Qiniu.uploader({ disable_statistics_report: false, // 禁止自動發送上傳統計信息到七牛,默認容許發送 runtimes: 'html5,flash,html4', // 上傳模式,依次退化 browse_button: 'uploadImage', // 上傳選擇的點選按鈕,必需 container: 'container', // 上傳區域DOM ID,默認是browser_button的父元素 max_file_size: '100mb', // 最大文件體積限制 flash_swf_url: 'Moxie.swf', // 引入flash,相對路徑 dragdrop: false, // 關閉可拖曳上傳 chunk_size: '4mb', // 分塊上傳時,每塊的體積 multi_selection: !(moxie.core.utils.Env.OS.toLowerCase() === "ios"), uptoken_url: 'XXX', // 在初始化時,uptoken,uptoken_url,uptoken_func三個參數中必須有一個被設置,uptoken是上傳憑證,由其餘程序生成;uptoken_url是提供了獲取上傳憑證的地址,若是須要定製獲取uptoken的過程則能夠設置uptoken_func;其優先級爲uptoken > uptoken_url > uptoken_func domain: 'XXX', // bucket域名,下載資源時用到,必需 get_new_uptoken: true, // 設置上傳文件的時候是否每次都從新獲取新的uptoken auto_start: true, // 選擇文件後自動上傳,若關閉須要本身綁定事件觸發上傳 max_retries: 3, // 上傳失敗最大重試次數 save_key: true, resize: { // 想限制上傳圖片尺寸,直接用resize這個屬性 width: 300, height: 300 }, init: { 'FilesAdded': function(up, files) { // 文件添加進隊列後,處理相關的事情 plupload.each(files, function(file) { console.log(file) }); }, 'BeforeUpload': function(up, file) { // 每一個文件上傳前,處理相關的事情 console.log("開始上傳以前"); $(".upload-progress").show(); }, 'UploadProgress': function(up, file) { // 每一個文件上傳時,處理相關的事情 console.log("上傳中"); $(".upload-progress").html("上傳進度:"+file.percent + "%"); }, 'FileUploaded': function(up, file, info) { // 每一個文件上傳成功後,處理相關的事情 console.log("上傳成功"); $(".upload-progress").hide(); var img = new Image(); //建立一個Image對象,實現圖片的預下載 img.src = "http://qiniu.com/"+res.key; $("#container").append(img); }, 'Error': function(up, err, errTip) { console.log("上傳出錯") }, 'UploadComplete': function() { //隊列文件處理完畢後,處理相關的事情 } } }); </script> </body> </html>
做者:Eternal丶
連接:https://www.jianshu.com/p/1e53415afb09
html