|
| 1 | +# oss 上传 |
| 2 | + |
| 3 | +- order: 10 |
| 4 | + |
| 5 | +需要先从后端获取 host/OSSAccessKeyId/policy/signature/key 参数,修改action和data,再利用upload能力上层 |
| 6 | + |
| 7 | +因为 demo 中的 action 为 oss 测试地址,不支持直接上传,所以控制台会报`Access-Control-Allow-Origin`的错误,真实环境中需要自己配置下访问控制 |
| 8 | + |
| 9 | +:::lang=en-us |
| 10 | +# oss upload |
| 11 | + |
| 12 | +- order: 10 |
| 13 | + |
| 14 | +get host/OSSAccessKeyId/policy/signature/key by ajax,then modify action/data |
| 15 | + |
| 16 | +::: |
| 17 | +--- |
| 18 | + |
| 19 | +````jsx |
| 20 | +import { Upload } from '@alifd/next'; |
| 21 | + |
| 22 | +class App extends React.Component { |
| 23 | + beforeUpload = (file, options) => { |
| 24 | + return new Promise((resolve, reject) => { |
| 25 | + setTimeout(() => { |
| 26 | + // mock ajax to get host/OSSAccessKeyId/policy/signature/key |
| 27 | + const dataFormAjaxResponse = { |
| 28 | + host: 'post-test.oss-cn-hangzhou.aliyuncs.com', |
| 29 | + OSSAccessKeyId:'6MKO******4AUk44', |
| 30 | + policy:'eyJleHBpcmF0aW9uIjoiMjAxNS0xMS0wNVQyMDoyMzoyM1oiLCJjxb25kaXRpb25zIjpbWyJjcb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInVzZXItZGlyXC8iXV19', |
| 31 | + signature:'I2u57FWjTKqX/AE6doIdyff151E=', |
| 32 | + key: 'user-dir/filename.jpg', |
| 33 | + }; |
| 34 | + |
| 35 | + const { host, OSSAccessKeyId, policy, signature, key, domain, } = dataFormAjaxResponse; |
| 36 | + |
| 37 | + // modify action and form data |
| 38 | + options.action = `//${host}`; |
| 39 | + options.data = { |
| 40 | + key, |
| 41 | + policy, |
| 42 | + OSSAccessKeyId, |
| 43 | + signature, |
| 44 | + }; |
| 45 | + |
| 46 | + // real url |
| 47 | + this.url = `//${domain}/${key}`; |
| 48 | + |
| 49 | + resolve(options); |
| 50 | + }, 300); |
| 51 | + }); |
| 52 | + } |
| 53 | + onSuccess = (file, value) => { |
| 54 | + console.log(file, value); |
| 55 | + }; |
| 56 | + formatter = (res, file) => ({ |
| 57 | + success: true, |
| 58 | + url: this.url |
| 59 | + }); |
| 60 | + render() { |
| 61 | + return ( |
| 62 | + <Upload |
| 63 | + beforeUpload={this.beforeUpload} |
| 64 | + onSuccess={this.onSuccess} |
| 65 | + formatter={this.formatter} |
| 66 | + shape="card" |
| 67 | + > |
| 68 | + oss demo |
| 69 | + </Upload> |
| 70 | + ); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +ReactDOM.render(<App/>, mountNode); |
| 75 | +```` |
0 commit comments