由于前端的终端多样化,导致oss在上传时操作有不同之处,不过相同点都是先获取阿里云服务器地址,然后上传表单数据,最后得到网络图片地址,今天分享一下阿里云oss在H5和小程序端的上传流程,小程序使用的react,H5使用的vue,直接上代码。
1.小程序端流程
getOss () { // 获取oss服务 const ossApi = 'https://m-zy-api.yisutech.com/api/middle/oss/getHjbzOssRedirectSign'; return new Promise((resolve, reject) => { Taro.request({ url: ossApi }).then(res => { resolve(res.data.model) }).catch(err => { reject(err) }) }) }, upToOss (list) { // 上传oss服务器,返回网络url return new Promise((resolve) => { const resList = []; this.getOss().then(res => { list.forEach((item, index) => { const key = `${new Date().getTime()}${index}.jpg` Taro.uploadFile({ url: res.host, filePath: item, name: 'file', formData: { name: item, key: key, OSSAccessKeyId: res.accessid, policy: res.policy, success_action_status: '200', Signature: res.signature } }).then(() => { const address = res.host + '/' + key; resList.push(address); if (resList.length === list.length) { resolve(resList); } }) }) }).catch(() => { this.toast('获取oss服务失败') }) }) } H5端流程 getOssInfo () { // 请求OSS服务器信息 return new Promise((resolve, reject) => { this.$http('GET', this.api.getOssRedirectSign, {}).then( res => { this.accessid = res.data.model.accessid this.signature = res.data.model.signature this.dir = res.data.model.dir this.policy = res.data.model.policy this.host = res.data.model.host this.$nextTick(() => { resolve() }) }, err => { reject(err) } ) }) }, updataImage (blob) { // 上传oss this.getOssInfo().then(() => { const formData = new FormData() const time = new Date().getTime() const filename = `${time}${Math.round(Math.random() * 100000000)}.jpg` const key = `${this.dir}${filename}` formData.append('key', key) formData.append('name', filename) formData.append('policy', this.policy) formData.append('OSSAccessKeyId', this.accessid) formData.append('success_action_status', '200') formData.append('callback', '') formData.append('signature', this.signature) formData.append('file', blob) axios .create({ withCredentials: true, headers: { 'Content-Type': 'multipart/form-data' } }) .post(this.host, formData) .then(res => { if (res.status === 200) { this.shareImg = this.host + '/' + key console.log('上传完毕') } }) }) }