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() // 创建form对象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 项目里的文件路径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启动运行
后端启动服务那些我就 不贴 了,这是功能代码,直接用上