JS node 后端签名前端文件直传ali-oss解决方案
生活随笔
收集整理的這篇文章主要介紹了
JS node 后端签名前端文件直传ali-oss解决方案
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1:首先打開跨域
上面搞好了開始寫代碼
html
<input type="file" id="upload" onchange="uploadfile()">js
function uploadfile() {var file = document.getElementById('upload').files[0]$.ajax({url: '/policy',data: '',type: 'get',dataType: 'json',success: function (data) {let param = new FormData() // 創(chuàng)建form對(duì)象param.append('OSSAccessKeyId', data.OSSAccessKeyId)param.append('policy', data.policy)param.append('key', data.startsWith + data.saveName)param.append('success_action_status', 200)param.append('signature', data.signature)param.append('file', file, data.saveName)const xhr = new XMLHttpRequest()xhr.open('post', data.host, true)xhr.upload.addEventListener('progress', (evt) => {this.progress = Math.round((evt.loaded) * 100 / evt.total)}, false)xhr.addEventListener('load', (e) => {if (e.target.status !== 200) {console.log(e.target.response)console.log('上傳失敗!')return}if (e.target.status === 200) {console.log(data.host + '/' + data.startsWith + data.saveName)this.imgUrl = data.host + '/' + data.startsWith + data.saveName}}, false)xhr.send(param)}})}node?
const crypto = require('crypto'); const path = require('path'); const axios = require('axios'); let oss = {OSSAccessKeyId: 'deAIrr6Bkdemo', //上圖顯示的位置,去獲取你自己的ID,下同secret: 'bPaJweew3lwaZweiPjeNClsluyUhne33M',//上圖顯示的位置host: 'https://demo.oss-cn-beijing.aliyuncs.com' // //上圖顯示的位置 }; var policy = async function (ctx, next) {const dirPath = 'img/' //bucket 項(xiàng)目里的文件路徑const {OSSAccessKeyId, host, secret} = oss;let end = new Date().getTime() + 360000let expiration = new Date(end).toISOString()let policyString = {expiration,conditions: [['content-length-range', 0, 1048576000],['starts-with', '$key', dirPath]]}policyString = JSON.stringify(policyString)const policy = new Buffer(policyString).toString('base64')const signature = crypto.createHmac('sha1', secret).update(policy).digest('base64')ctx.body = {OSSAccessKeyId: OSSAccessKeyId,host,policy,signature,saveName: end,startsWith: dirPath}; }module.exports = {policy: policy}OK啟動(dòng)運(yùn)行
后端啟動(dòng)服務(wù)那些我就 不貼 了,這是功能代碼,直接用上
?
總結(jié)
以上是生活随笔為你收集整理的JS node 后端签名前端文件直传ali-oss解决方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 数字图像处理 冈萨雷斯 第三版 书中配套
- 下一篇: Linux决心书/李世超