From cfed99b25368737449573bfdd451373f48ce55e1 Mon Sep 17 00:00:00 2001 From: Grayson Chen Date: Wed, 9 Dec 2015 00:34:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=94=9F=E6=88=90=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0url=20http://docs.upyun.com/api/form=5Fapi/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 35 +++++++++++++++++++++++++++++++++++ lib/upyun/form.rb | 22 ++++++++++++++++------ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 72bc2e9..a04ca0f 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,41 @@ upyun.upload(File.new('filepath.png')) * `sign`: 签名参数,详情见 [sign与non-sign参数说明](http://docs.upyun.com/api/form_api/#note6) * 如果在请求中指定了 `ext-param`, 那么返回的结构中也会有 `ext-param` 字段,详情见 [ext-param](http://docs.upyun.com/api/form_api/#note5) +##### 生成上传URL +客户端可以直接上传文件到upyun(而不先上传自己的主机再传到upyun)。 + +```ruby +def upyun_upload_url + file_key = SecureRandom.uuid + upyun = Upyun::Form.new('form-api-secret', 'bucket') + upyun_json = upyun.generate_upload_url('save-key'=> file_key,'content-type'=>'audio/mp3') + + remote_link = 'https://' + bucket + '.b0.upaiyun.com/'+file_key + upload_url = 'https://v0.api.upyun.com/' + bucket + render json: { remoteLink: remote_link, + uploadUrl: upload_url, + policy: upyun_json[:policy], + signature: upyun_json[:signature] } +end +``` + +```javascript +$.get('/user/'+id+'/audio/upyun_upload_url', (function(question, response) { + var uploadData = new AudioData(); + uploadData.append('signature', response.signature); + uploadData.append('policy', response.policy); + uploadData.append('file', mp3Blob); + $.ajax({ + url: response.uploadUrl, + type: 'POST', + data: uploadData, + contentType: 'audio/mpeg', + processData: false + }); +} +``` + + ##### 自定义参数 可以在上传的时候指定一些策略参数: diff --git a/lib/upyun/form.rb b/lib/upyun/form.rb index 4dc90e6..78ca276 100644 --- a/lib/upyun/form.rb +++ b/lib/upyun/form.rb @@ -42,13 +42,15 @@ def initialize(password, bucket, options={timeout: 60}) @endpoint = ED_AUTO end - def upload(file, opts={}) - base_opts = HashWithIndifferentAccess.new({ - 'bucket' => @bucket, - 'save-key' => '/{year}/{mon}/{day}/{filename}{.suffix}', - 'expiration' => Time.now.to_i + 600 - }) + def generate_upload_url(opts={}) + payload = { + policy: policy(base_opts.merge(opts)), + signature: signature, + url: "#{base_opts['save-key']}", + } + end + def upload(file, opts={}) payload = { policy: policy(base_opts.merge(opts)), signature: signature, @@ -82,6 +84,14 @@ def upload(file, opts={}) end private + def base_opts + HashWithIndifferentAccess.new({ + 'bucket' => @bucket, + 'save-key' => '/{year}/{mon}/{day}/{filename}{.suffix}', + 'expiration' => Time.now.to_i + 600 + }) + end + def policy(opts) @_policy = Base64.strict_encode64(policy_json(opts)) end