微信小程序环境下将文件上传到OSS的方法步骤
程序员文章站
2023-12-18 16:49:46
步骤 1: 配置 bucket 跨域
客户端进行表单直传到 oss 时,会从浏览器向 oss 发送带有 origin 的请求消息。oss 对带有 origin 头的请求消...
步骤 1: 配置 bucket 跨域
客户端进行表单直传到 oss 时,会从浏览器向 oss 发送带有 origin 的请求消息。oss 对带有 origin 头的请求消息会进行跨域规则(cors)的验证。因此需要为 bucket 设置跨域规则以支持 post 方法。
步骤 2:配置外网域名到小程序的上传域名白名单中
通过 oss 控制台查看外网域名。
登录微信小程序平台,配置小程序的上传域名白名单。
步骤 3:使用 web 端直传实践方案 demo 进行上传测试
下载应用服务器代码
修改 demo 中 upload.js 的密钥和地址。
进行上传测试。
获取上传需要的签名(signature)和加密策略(policy)
使用微信小程序上传图片
使用 chooseimage api 进行图片选择,然后调用 uploadfile 进行文件上传
upload.js
accessid= ''; accesskey= ''; host = ''; g_dirname = '' g_object_name = '' g_object_name_type = '' now = timestamp = date.parse(new date()) / 1000; var policytext = { "expiration": "2020-01-01t12:00:00.000z", //设置该policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了 "conditions": [ ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制 ] }; var policybase64 = base64.encode(json.stringify(policytext)) message = policybase64 var bytes = crypto.hmac(crypto.sha1, message, accesskey, { asbytes: true }) ; var signature = crypto.util.bytestobase64(bytes); 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 get_dirname() { dir = document.getelementbyid("dirname").value; if (dir != '' && dir.indexof('/') != dir.length - 1) { dir = dir + '/' } //alert(dir) g_dirname = dir } function random_string(len) { len = len || 32; var chars = 'abcdefghjkmnpqrstwxyzabcdefhijkmnprstwxyz2345678'; var maxpos = chars.length; var pwd = ''; for (i = 0; i < len; i++) { pwd += chars.charat(math.floor(math.random() * maxpos)); } return pwd; } function get_suffix(filename) { pos = filename.lastindexof('.') suffix = '' if (pos != -1) { suffix = filename.substring(pos) } return suffix; } function calculate_object_name(filename) { if (g_object_name_type == 'local_name') { g_object_name += "${filename}" } else if (g_object_name_type == 'random_name') { suffix = get_suffix(filename) g_object_name = g_dirname + random_string(10) + suffix } return '' } function get_uploaded_object_name(filename) { if (g_object_name_type == 'local_name') { tmp_name = g_object_name tmp_name = tmp_name.replace("${filename}", filename); return tmp_name } else if(g_object_name_type == 'random_name') { return g_object_name } } function set_upload_param(up, filename, ret) { g_object_name = g_dirname; 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 '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', //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', init: { postinit: function() { document.getelementbyid('ossfile').innerhtml = ''; document.getelementbyid('postfiles').onclick = function() { set_upload_param(uploader, '', false); return false; }; }, 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>'; }); }, beforeupload: function(up, file) { check_object_radio(); get_dirname(); set_upload_param(up, file.name, true); }, 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) { if (info.status == 200) { document.getelementbyid(file.id).getelementsbytagname('b')[0].innerhtml = 'upload to oss success, object name:' + get_uploaded_object_name(file.name); } else { document.getelementbyid(file.id).getelementsbytagname('b')[0].innerhtml = info.response; } }, error: function(up, err) { document.getelementbyid('console').appendchild(document.createtextnode("\nerror xml:" + err.response)); } } }); uploader.init();
index.html
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>oss web直传</title> <link rel="stylesheet" type="text/css" href="style.css"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> </head> <body> <h2>oss web直传---直接在js签名</h2> <ol> <li>基于plupload封装 </li> <li>支持html5,flash,silverlight,html4 等协议上传</li> <li>可以运行在pc浏览器,手机浏览器,微信</li> <li>可以选择多文件上传</li> <li>显示上传进度条</li> <li>可以控制上传文件的大小</li> <li>最关键的是,让你10分钟之内就能移植到你的系统,实现以上牛逼的功能!</li> <li>注意一点,bucket必须设置了cors(post打勾),不然没有办法上传</li> <li>注意一点,把upload.js 里面的host/accessid/accesskey改成您上传所需要的信息即可</li> <li>此方法是直接在前端签名,有accessid/accesskey泄漏的风险, 线上生产请使用后端签名例子<a href="https://help.aliyun.com/document_detail/oss/practice/pc_web_upload/js_php_upload.html">点击查看详细文档</a></li> </ol> <br> <form name=theform> <input type="radio" name="myradio" value="local_name" checked=true/> 上传文件名字保持本地文件名字 <input type="radio" name="myradio" value="random_name" /> 上传文件名字是随机文件名 <br/> 上传到指定目录:<input type="text" id='dirname' placeholder="如果不填,默认是上传到根目录" size=50> </form> <h4>您所选择的文件列表:</h4> <div id="ossfile">你的浏览器不支持flash,silverlight或者html5!</div> <br/> <div id="container"> <a id="selectfiles" href="javascript:void(0);" class='btn'>选择文件</a> <a id="postfiles" href="javascript:void(0);" class='btn'>开始上传</a> </div> <pre id="console"></pre> <p> </p> </body> <script type="text/javascript" src="lib/crypto1/crypto/crypto.js"></script> <script type="text/javascript" src="lib/crypto1/hmac/hmac.js"></script> <script type="text/javascript" src="lib/crypto1/sha1/sha1.js"></script> <script type="text/javascript" src="lib/base64.js"></script> <script type="text/javascript" src="lib/plupload-2.1.2/js/plupload.full.min.js"></script> <script type="text/javascript" src="upload.js"></script> </html>
实现点击按钮选择图片后显示图片并且可以预览该图片
跳转的按钮在子组件
this.$navigate({url:"content"}) this.$parent.$navigate({url:"content"}) wepy.navigateto({ url: '/pages/content' })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。