select multiple photo from desktop or phone, and preview, and upload to qiniu 先预览, 再上传
deploy () {
this.$vux.loading.show()
let accessKey = '$ck',
secretKey = '$sk',
putPolicy = {
scope: '$scope',
deadline: new Date().getTime() + 3600 * 1000,
returnBody: `{
"name": $(fname),
"size": $(fsize),
"w": $(imageInfo.width),
"h": $(imageInfo.height),
"hash": $(etag)
}`
}
let token = genUpToken(accessKey, secretKey, putPolicy)
this.fileList.forEach(file => {
let formData = new FormData(),
// 时间戳作为名字
name = new Date().getTime() + '.jpg'
// FormData传输文件数据
formData.append('file', file)
formData.append('token',token)
formData.append('key', name)
var xhr = new XMLHttpRequest()
xhr.onload = () => {
this.imgHttpUrl.push('$fullImageUrl')
}
xhr.open("post", '$uploadUrl', true)
xhr.send(formData)
})
// 全部上传成功
let int = setInterval(() => {
if (this.imgHttpUrl.length == this.fileList.length) {
this.$vux.loading.hide()
clearInterval(int)
}
}, 300)
}
/**
* 上传凭证算法实现参考
* 请注意External Resources项中引用的第三方CryptoJS库
* <script src="http://qtestbucket.qiniudn.com/demo/CryptoJS.js" async></script>
*/
var genUpToken = function(accessKey, secretKey, putPolicy) {
//SETP 2
var put_policy = JSON.stringify(putPolicy);
//SETP 3
// 用浏览器自带base64 api
var encoded = window.btoa(unescape(encodeURIComponent(put_policy)));
//SETP 4
var hash = CryptoJS.HmacSHA1(encoded, secretKey);
var encoded_signed = hash.toString(CryptoJS.enc.Base64);
//SETP 5
var upload_token = accessKey + ":" + safe64(encoded_signed) + ":" + encoded;
console && console.log("upload_token=", upload_token)
return upload_token;
};
var safe64 = function(base64) {
base64 = base64.replace(/\+/g, "-");
base64 = base64.replace(/\//g, "_");
return base64;
}onchange (e) {
let files = document.getElementById('file').files
this.imgDataUrl = []
this.fileList = []
for (let index of Object.keys(files)) {
// 最多只选择三张图片
if (index > 2) break
let reader = new FileReader(),
file = files[index]
reader.onload = (e) => {
this.imgDataUrl.push(e.target.result)
this.fileList.push(file)
}
reader.readAsDataURL(file)
}
}<input name="file" type="file" @change="onchange" id="file" multiple hidden accept="image/png, image/jpeg, image/gif, image/jpg"/>
<label for="file">点击预览</label>
<div class="img-box" v-for="src in imgDataUrl">
<!--使用data:image/jpeg;base64形式预览-->
<img :src="src" width="100">
</div>
<button type="reset" @click="upload">上传到七牛云</button>