Under micro-channel environment applet to upload files to OSS

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed, up to tertiary niche: Reverse rest of his life, except you have https://blog.csdn.net/qq_36232611/article/details/90708422

Step 1: Configure cross-domain Bucket
client when the forward pass to form OSS, sends a request message from the Origin browser with the OSS. Origin OSS request message with header may be verified by cross-domain rules (CORS) a. Therefore it needs to be set to support cross-domain rules Bucket Post method.

image.png

Step 2: Configure the domain name to upload external domain whitelist small program

  1. View outside the domain name by OSS console.
    image

  2. Log in micro letter applet platform, configuration applet upload domain whitelist.image

Step 3: Using the Web forward pass end practices Demo upload test

Download the application server code

Demo in upload.js modify keys and address.
image

Upload test.

image.png

image.png

image.png

Get upload the required signature (signature) and encryption strategy (policy)

The use of micro-channel applet upload pictures
using chooseImage API pictures were selected, and then call uploadFile for file upload

image

https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.155a7eaeW7iaPX

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>&nbsp;</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>

Display image after clicking the button to select the picture and realize you can preview the picture

image.png

image.png

image.png

image.png

Jump button subassembly

this.$navigate({url:"content"})

this.$parent.$navigate({url:"content"})

wepy.navigateTo({
url: '/pages/content'
})

Please thumbs up! Because your encouragement is the greatest power of my writing!

No public official micro letter

Blowing force exchange group: 711,613,774

Blowing force exchange group

Guess you like

Origin blog.csdn.net/qq_36232611/article/details/90708422