Method: Baidu::PCS::Client#upload

Defined in:
lib/baidu/pcs/client.rb

#upload(file, options = {}) ⇒ Hash

Note:

百度PCS服务目前支持最大2G的单个文件上传

Note:

文件大小超过 128MB 时,自动启用文件分块上传;如果不想启用文件分块上传,可以通过 block_upload: false 来关闭

上传单个文件

Examples:

File.open('/opt/ubuntu-12.04.3-server-amd64.iso', 'r') do |f|
  c.upload(f, block_upload: true)
end

返回的原始 JSON

{
  "fs_id": 3916799999,
  "path": "/apps/album/1.png",
  "ctime": 1384493574,
  "mtime": 1384493574,
  "md5": "6c37219ba0d3dfdfa95ff6912e2c42b9",
  "size": 4914,
  "request_id": 3036629135
}

:fs_id 文件在PCS的临时唯一标识ID
:path  该文件的绝对路径
:ctime 文件创建时间
:mtime 文件修改时间
:md5   文件的md5签名
:size  文件字节大小

Parameters:

  • file (File)

    待上传的文件

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :path (String)

    上传文件路径,含上传的文件名称(相对于应用根目录),默认为 file 的文件名

  • :overwrite (Boolean)

    true: 表示覆盖同名文件,false: 表示生成文件副本并进行重命名,命名规则为“文件名_日期.后缀”,默认为 false

  • :block_upload (Boolean)

    对文件分块上传,仅当 file 大小超过 8MB 时,此设置有效;分块大小取决于文件大小,4GB 以下文件分块大小为 4MB

  • :retry_times (Fixnum)

    分块上传时,出错自动重试次数,默认 5

  • :retry_waitsec (Fixnum)

    分块上传时,出错自动重试暂停秒数,默认 30

Returns:

  • (Hash)

Raises:

  • (ArgumentError)

See Also:



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/baidu/pcs/client.rb', line 123

def upload(file, options={})
  raise ArgumentError, 'file must be an instance of File' unless file.instance_of? File
  path = options[:path] || File.basename(file)
  size = file.size
  if (options[:block_upload] && size >= 4*1024*1024*2) ||  # at least 2 blocks
     (options[:block_upload].nil? && size >= 128*1024*1024)
    block_size = 4*1024*1024
    while block_size * 1024 < size  # at most 1024 blocks1
      block_size *= 2
    end
    offset, block_list = 0, []
    max_retry_times = options[:retry_times]   || 5
    retry_waitsec   = options[:retry_waitsec] || 30
    loop do
      with_retries(max_retry_times, retry_waitsec) do
        rest = upload_block IO.binread(file, block_size, offset)
        block_list << rest[:md5]
      end
      offset += block_size
      break if offset >= size
    end
    with_retries(max_retry_times, retry_waitsec) do
      create_super_file block_list, path, options[:overwrite]
    end
  else
    raise IOError, 'file is too large (larger than 2G)' if size > 2*1024*1024*1024
    query = build_upload_query 'upload', path, options[:overwrite]
    post "#{BASE_PATH}/file", query, { file: file }, site: Baidu::PCS::UPLOAD_SITE
  end
end