You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

654 lines
23 KiB

  1. package cos
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "sort"
  12. "time"
  13. )
  14. // ObjectService 相关 API
  15. type ObjectService service
  16. // ObjectGetOptions is the option of GetObject
  17. type ObjectGetOptions struct {
  18. ResponseContentType string `url:"response-content-type,omitempty" header:"-"`
  19. ResponseContentLanguage string `url:"response-content-language,omitempty" header:"-"`
  20. ResponseExpires string `url:"response-expires,omitempty" header:"-"`
  21. ResponseCacheControl string `url:"response-cache-control,omitempty" header:"-"`
  22. ResponseContentDisposition string `url:"response-content-disposition,omitempty" header:"-"`
  23. ResponseContentEncoding string `url:"response-content-encoding,omitempty" header:"-"`
  24. Range string `url:"-" header:"Range,omitempty"`
  25. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  26. // SSE-C
  27. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  28. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  29. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  30. }
  31. // presignedURLTestingOptions is the opt of presigned url
  32. type presignedURLTestingOptions struct {
  33. authTime *AuthTime
  34. }
  35. // Get Object 请求可以将一个文件(Object)下载至本地。
  36. // 该操作需要对目标 Object 具有读权限或目标 Object 对所有人都开放了读权限(公有读)。
  37. //
  38. // https://www.qcloud.com/document/product/436/7753
  39. func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  40. var u string
  41. if len(id) == 1 {
  42. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  43. } else if len(id) == 0 {
  44. u = "/" + encodeURIComponent(name)
  45. } else {
  46. return nil, errors.New("wrong params")
  47. }
  48. sendOpt := sendOptions{
  49. baseURL: s.client.BaseURL.BucketURL,
  50. uri: u,
  51. method: http.MethodGet,
  52. optQuery: opt,
  53. optHeader: opt,
  54. disableCloseBody: true,
  55. }
  56. resp, err := s.client.send(ctx, &sendOpt)
  57. return resp, err
  58. }
  59. // GetToFile download the object to local file
  60. func (s *ObjectService) GetToFile(ctx context.Context, name, localpath string, opt *ObjectGetOptions, id ...string) (*Response, error) {
  61. resp, err := s.Get(ctx, name, opt, id...)
  62. if err != nil {
  63. return resp, err
  64. }
  65. defer resp.Body.Close()
  66. // If file exist, overwrite it
  67. fd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
  68. if err != nil {
  69. return resp, err
  70. }
  71. _, err = io.Copy(fd, resp.Body)
  72. fd.Close()
  73. if err != nil {
  74. return resp, err
  75. }
  76. return resp, nil
  77. }
  78. // GetPresignedURL get the object presigned to down or upload file by url
  79. func (s *ObjectService) GetPresignedURL(ctx context.Context, httpMethod, name, ak, sk string, expired time.Duration, opt interface{}) (*url.URL, error) {
  80. sendOpt := sendOptions{
  81. baseURL: s.client.BaseURL.BucketURL,
  82. uri: "/" + encodeURIComponent(name),
  83. method: httpMethod,
  84. optQuery: opt,
  85. optHeader: opt,
  86. }
  87. req, err := s.client.newRequest(ctx, sendOpt.baseURL, sendOpt.uri, sendOpt.method, sendOpt.body, sendOpt.optQuery, sendOpt.optHeader)
  88. if err != nil {
  89. return nil, err
  90. }
  91. var authTime *AuthTime
  92. if opt != nil {
  93. if opt, ok := opt.(*presignedURLTestingOptions); ok {
  94. authTime = opt.authTime
  95. }
  96. }
  97. if authTime == nil {
  98. authTime = NewAuthTime(expired)
  99. }
  100. authorization := newAuthorization(ak, sk, req, authTime)
  101. sign := encodeURIComponent(authorization)
  102. if req.URL.RawQuery == "" {
  103. req.URL.RawQuery = fmt.Sprintf("sign=%s", sign)
  104. } else {
  105. req.URL.RawQuery = fmt.Sprintf("%s&sign=%s", req.URL.RawQuery, sign)
  106. }
  107. return req.URL, nil
  108. }
  109. // ObjectPutHeaderOptions the options of header of the put object
  110. type ObjectPutHeaderOptions struct {
  111. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  112. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  113. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  114. ContentType string `header:"Content-Type,omitempty" url:"-"`
  115. ContentMD5 string `header:"Content-MD5,omitempty" url:"-"`
  116. ContentLength int `header:"Content-Length,omitempty" url:"-"`
  117. Expect string `header:"Expect,omitempty" url:"-"`
  118. Expires string `header:"Expires,omitempty" url:"-"`
  119. XCosContentSHA1 string `header:"x-cos-content-sha1,omitempty" url:"-"`
  120. // 自定义的 x-cos-meta-* header
  121. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  122. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-"`
  123. // 可选值: Normal, Appendable
  124. //XCosObjectType string `header:"x-cos-object-type,omitempty" url:"-"`
  125. // Enable Server Side Encryption, Only supported: AES256
  126. XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
  127. // SSE-C
  128. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  129. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  130. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  131. //兼容其他自定义头部
  132. XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
  133. }
  134. // ObjectPutOptions the options of put object
  135. type ObjectPutOptions struct {
  136. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  137. *ObjectPutHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  138. }
  139. // Put Object请求可以将一个文件(Oject)上传至指定Bucket。
  140. //
  141. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  142. //
  143. // https://www.qcloud.com/document/product/436/7749
  144. func (s *ObjectService) Put(ctx context.Context, name string, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  145. sendOpt := sendOptions{
  146. baseURL: s.client.BaseURL.BucketURL,
  147. uri: "/" + encodeURIComponent(name),
  148. method: http.MethodPut,
  149. body: r,
  150. optHeader: opt,
  151. }
  152. resp, err := s.client.send(ctx, &sendOpt)
  153. return resp, err
  154. }
  155. // PutFromFile put object from local file
  156. // Notice that when use this put large file need set non-body of debug req/resp, otherwise will out of memory
  157. func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, opt *ObjectPutOptions) (*Response, error) {
  158. fd, err := os.Open(filePath)
  159. if err != nil {
  160. return nil, err
  161. }
  162. defer fd.Close()
  163. return s.Put(ctx, name, fd, opt)
  164. }
  165. // ObjectCopyHeaderOptions is the head option of the Copy
  166. type ObjectCopyHeaderOptions struct {
  167. // When use replace directive to update meta infos
  168. CacheControl string `header:"Cache-Control,omitempty" url:"-"`
  169. ContentDisposition string `header:"Content-Disposition,omitempty" url:"-"`
  170. ContentEncoding string `header:"Content-Encoding,omitempty" url:"-"`
  171. ContentType string `header:"Content-Type,omitempty" url:"-"`
  172. Expires string `header:"Expires,omitempty" url:"-"`
  173. Expect string `header:"Expect,omitempty" url:"-"`
  174. XCosMetadataDirective string `header:"x-cos-metadata-directive,omitempty" url:"-" xml:"-"`
  175. XCosCopySourceIfModifiedSince string `header:"x-cos-copy-source-If-Modified-Since,omitempty" url:"-" xml:"-"`
  176. XCosCopySourceIfUnmodifiedSince string `header:"x-cos-copy-source-If-Unmodified-Since,omitempty" url:"-" xml:"-"`
  177. XCosCopySourceIfMatch string `header:"x-cos-copy-source-If-Match,omitempty" url:"-" xml:"-"`
  178. XCosCopySourceIfNoneMatch string `header:"x-cos-copy-source-If-None-Match,omitempty" url:"-" xml:"-"`
  179. XCosStorageClass string `header:"x-cos-storage-class,omitempty" url:"-" xml:"-"`
  180. // 自定义的 x-cos-meta-* header
  181. XCosMetaXXX *http.Header `header:"x-cos-meta-*,omitempty" url:"-"`
  182. XCosCopySource string `header:"x-cos-copy-source" url:"-" xml:"-"`
  183. XCosServerSideEncryption string `header:"x-cos-server-side-encryption,omitempty" url:"-" xml:"-"`
  184. // SSE-C
  185. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  186. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  187. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  188. XCosCopySourceSSECustomerAglo string `header:"x-cos-copy-source-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  189. XCosCopySourceSSECustomerKey string `header:"x-cos-copy-source-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  190. XCosCopySourceSSECustomerKeyMD5 string `header:"x-cos-copy-source-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  191. }
  192. // ObjectCopyOptions is the option of Copy, choose header or body
  193. type ObjectCopyOptions struct {
  194. *ObjectCopyHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  195. *ACLHeaderOptions `header:",omitempty" url:"-" xml:"-"`
  196. }
  197. // ObjectCopyResult is the result of Copy
  198. type ObjectCopyResult struct {
  199. XMLName xml.Name `xml:"CopyObjectResult"`
  200. ETag string `xml:"ETag,omitempty"`
  201. LastModified string `xml:"LastModified,omitempty"`
  202. }
  203. // Copy 调用 PutObjectCopy 请求实现将一个文件从源路径复制到目标路径。建议文件大小 1M 到 5G,
  204. // 超过 5G 的文件请使用分块上传 Upload - Copy。在拷贝的过程中,文件元属性和 ACL 可以被修改。
  205. //
  206. // 用户可以通过该接口实现文件移动,文件重命名,修改文件属性和创建副本。
  207. //
  208. // 注意:在跨帐号复制的时候,需要先设置被复制文件的权限为公有读,或者对目标帐号赋权,同帐号则不需要。
  209. //
  210. // https://cloud.tencent.com/document/product/436/10881
  211. func (s *ObjectService) Copy(ctx context.Context, name, sourceURL string, opt *ObjectCopyOptions, id ...string) (*ObjectCopyResult, *Response, error) {
  212. var u string
  213. if len(id) == 1 {
  214. u = fmt.Sprintf("%s?versionId=%s", encodeURIComponent(sourceURL), id[0])
  215. } else if len(id) == 0 {
  216. u = encodeURIComponent(sourceURL)
  217. } else {
  218. return nil, nil, errors.New("wrong params")
  219. }
  220. var res ObjectCopyResult
  221. if opt == nil {
  222. opt = new(ObjectCopyOptions)
  223. }
  224. if opt.ObjectCopyHeaderOptions == nil {
  225. opt.ObjectCopyHeaderOptions = new(ObjectCopyHeaderOptions)
  226. }
  227. opt.XCosCopySource = u
  228. sendOpt := sendOptions{
  229. baseURL: s.client.BaseURL.BucketURL,
  230. uri: "/" + encodeURIComponent(name),
  231. method: http.MethodPut,
  232. body: nil,
  233. optHeader: opt,
  234. result: &res,
  235. }
  236. resp, err := s.client.send(ctx, &sendOpt)
  237. // If the error occurs during the copy operation, the error response is embedded in the 200 OK response. This means that a 200 OK response can contain either a success or an error.
  238. if err == nil && resp.StatusCode == 200 {
  239. if res.ETag == "" {
  240. return &res, resp, errors.New("response 200 OK, but body contains an error")
  241. }
  242. }
  243. return &res, resp, err
  244. }
  245. // Delete Object请求可以将一个文件(Object)删除。
  246. //
  247. // https://www.qcloud.com/document/product/436/7743
  248. func (s *ObjectService) Delete(ctx context.Context, name string) (*Response, error) {
  249. // When use "" string might call the delete bucket interface
  250. if len(name) == 0 {
  251. return nil, errors.New("empty object name")
  252. }
  253. sendOpt := sendOptions{
  254. baseURL: s.client.BaseURL.BucketURL,
  255. uri: "/" + encodeURIComponent(name),
  256. method: http.MethodDelete,
  257. }
  258. resp, err := s.client.send(ctx, &sendOpt)
  259. return resp, err
  260. }
  261. // ObjectHeadOptions is the option of HeadObject
  262. type ObjectHeadOptions struct {
  263. IfModifiedSince string `url:"-" header:"If-Modified-Since,omitempty"`
  264. // SSE-C
  265. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  266. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  267. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  268. }
  269. // Head Object请求可以取回对应Object的元数据,Head的权限与Get的权限一致
  270. //
  271. // https://www.qcloud.com/document/product/436/7745
  272. func (s *ObjectService) Head(ctx context.Context, name string, opt *ObjectHeadOptions, id ...string) (*Response, error) {
  273. var u string
  274. if len(id) == 1 {
  275. u = fmt.Sprintf("/%s?versionId=%s", encodeURIComponent(name), id[0])
  276. } else if len(id) == 0 {
  277. u = "/" + encodeURIComponent(name)
  278. } else {
  279. return nil, errors.New("wrong params")
  280. }
  281. sendOpt := sendOptions{
  282. baseURL: s.client.BaseURL.BucketURL,
  283. uri: u,
  284. method: http.MethodHead,
  285. optHeader: opt,
  286. }
  287. resp, err := s.client.send(ctx, &sendOpt)
  288. if resp != nil && resp.Header["X-Cos-Object-Type"] != nil && resp.Header["X-Cos-Object-Type"][0] == "appendable" {
  289. resp.Header.Add("x-cos-next-append-position", resp.Header["Content-Length"][0])
  290. }
  291. return resp, err
  292. }
  293. // ObjectOptionsOptions is the option of object options
  294. type ObjectOptionsOptions struct {
  295. Origin string `url:"-" header:"Origin"`
  296. AccessControlRequestMethod string `url:"-" header:"Access-Control-Request-Method"`
  297. AccessControlRequestHeaders string `url:"-" header:"Access-Control-Request-Headers,omitempty"`
  298. }
  299. // Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  300. //
  301. // 当CORS配置不存在时,请求返回403 Forbidden。
  302. //
  303. // https://www.qcloud.com/document/product/436/8288
  304. func (s *ObjectService) Options(ctx context.Context, name string, opt *ObjectOptionsOptions) (*Response, error) {
  305. sendOpt := sendOptions{
  306. baseURL: s.client.BaseURL.BucketURL,
  307. uri: "/" + encodeURIComponent(name),
  308. method: http.MethodOptions,
  309. optHeader: opt,
  310. }
  311. resp, err := s.client.send(ctx, &sendOpt)
  312. return resp, err
  313. }
  314. // CASJobParameters support three way: Standard(in 35 hours), Expedited(quick way, in 15 mins), Bulk(in 5-12 hours_
  315. type CASJobParameters struct {
  316. Tier string `xml:"Tier"`
  317. }
  318. // ObjectRestoreOptions is the option of object restore
  319. type ObjectRestoreOptions struct {
  320. XMLName xml.Name `xml:"RestoreRequest"`
  321. Days int `xml:"Days"`
  322. Tier *CASJobParameters `xml:"CASJobParameters"`
  323. }
  324. // PutRestore API can recover an object of type archived by COS archive.
  325. //
  326. // https://cloud.tencent.com/document/product/436/12633
  327. func (s *ObjectService) PostRestore(ctx context.Context, name string, opt *ObjectRestoreOptions) (*Response, error) {
  328. u := fmt.Sprintf("/%s?restore", encodeURIComponent(name))
  329. sendOpt := sendOptions{
  330. baseURL: s.client.BaseURL.BucketURL,
  331. uri: u,
  332. method: http.MethodPost,
  333. body: opt,
  334. }
  335. resp, err := s.client.send(ctx, &sendOpt)
  336. return resp, err
  337. }
  338. // TODO Append 接口在优化未开放使用
  339. //
  340. // Append请求可以将一个文件(Object)以分块追加的方式上传至 Bucket 中。使用Append Upload的文件必须事前被设定为Appendable。
  341. // 当Appendable的文件被执行Put Object的操作以后,文件被覆盖,属性改变为Normal。
  342. //
  343. // 文件属性可以在Head Object操作中被查询到,当您发起Head Object请求时,会返回自定义Header『x-cos-object-type』,该Header只有两个枚举值:Normal或者Appendable。
  344. //
  345. // 追加上传建议文件大小1M - 5G。如果position的值和当前Object的长度不致,COS会返回409错误。
  346. // 如果Append一个Normal的Object,COS会返回409 ObjectNotAppendable。
  347. //
  348. // Appendable的文件不可以被复制,不参与版本管理,不参与生命周期管理,不可跨区域复制。
  349. //
  350. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength
  351. //
  352. // https://www.qcloud.com/document/product/436/7741
  353. // func (s *ObjectService) Append(ctx context.Context, name string, position int, r io.Reader, opt *ObjectPutOptions) (*Response, error) {
  354. // u := fmt.Sprintf("/%s?append&position=%d", encodeURIComponent(name), position)
  355. // if position != 0{
  356. // opt = nil
  357. // }
  358. // sendOpt := sendOptions{
  359. // baseURL: s.client.BaseURL.BucketURL,
  360. // uri: u,
  361. // method: http.MethodPost,
  362. // optHeader: opt,
  363. // body: r,
  364. // }
  365. // resp, err := s.client.send(ctx, &sendOpt)
  366. // return resp, err
  367. // }
  368. // ObjectDeleteMultiOptions is the option of DeleteMulti
  369. type ObjectDeleteMultiOptions struct {
  370. XMLName xml.Name `xml:"Delete" header:"-"`
  371. Quiet bool `xml:"Quiet" header:"-"`
  372. Objects []Object `xml:"Object" header:"-"`
  373. //XCosSha1 string `xml:"-" header:"x-cos-sha1"`
  374. }
  375. // ObjectDeleteMultiResult is the result of DeleteMulti
  376. type ObjectDeleteMultiResult struct {
  377. XMLName xml.Name `xml:"DeleteResult"`
  378. DeletedObjects []Object `xml:"Deleted,omitempty"`
  379. Errors []struct {
  380. Key string
  381. Code string
  382. Message string
  383. } `xml:"Error,omitempty"`
  384. }
  385. // DeleteMulti 请求实现批量删除文件,最大支持单次删除1000个文件。
  386. // 对于返回结果,COS提供Verbose和Quiet两种结果模式。Verbose模式将返回每个Object的删除结果;
  387. // Quiet模式只返回报错的Object信息。
  388. // https://www.qcloud.com/document/product/436/8289
  389. func (s *ObjectService) DeleteMulti(ctx context.Context, opt *ObjectDeleteMultiOptions) (*ObjectDeleteMultiResult, *Response, error) {
  390. var res ObjectDeleteMultiResult
  391. sendOpt := sendOptions{
  392. baseURL: s.client.BaseURL.BucketURL,
  393. uri: "/?delete",
  394. method: http.MethodPost,
  395. body: opt,
  396. result: &res,
  397. }
  398. resp, err := s.client.send(ctx, &sendOpt)
  399. return &res, resp, err
  400. }
  401. // Object is the meta info of the object
  402. type Object struct {
  403. Key string `xml:",omitempty"`
  404. ETag string `xml:",omitempty"`
  405. Size int `xml:",omitempty"`
  406. PartNumber int `xml:",omitempty"`
  407. LastModified string `xml:",omitempty"`
  408. StorageClass string `xml:",omitempty"`
  409. Owner *Owner `xml:",omitempty"`
  410. }
  411. // MultiUploadOptions is the option of the multiupload,
  412. // ThreadPoolSize default is one
  413. type MultiUploadOptions struct {
  414. OptIni *InitiateMultipartUploadOptions
  415. PartSize int64
  416. ThreadPoolSize int
  417. }
  418. type Chunk struct {
  419. Number int
  420. OffSet int64
  421. Size int64
  422. }
  423. // jobs
  424. type Jobs struct {
  425. Name string
  426. UploadId string
  427. FilePath string
  428. RetryTimes int
  429. Chunk Chunk
  430. Data io.Reader
  431. Opt *ObjectUploadPartOptions
  432. }
  433. type Results struct {
  434. PartNumber int
  435. Resp *Response
  436. }
  437. func worker(s *ObjectService, jobs <-chan *Jobs, results chan<- *Results) {
  438. for j := range jobs {
  439. fd, err := os.Open(j.FilePath)
  440. var res Results
  441. if err != nil {
  442. res.PartNumber = j.Chunk.Number
  443. res.Resp = nil
  444. results <- &res
  445. }
  446. fd.Seek(j.Chunk.OffSet, os.SEEK_SET)
  447. // UploadPart do not support the chunk trsf, so need to add the content-length
  448. j.Opt.ContentLength = int(j.Chunk.Size)
  449. rt := j.RetryTimes
  450. for {
  451. resp, err := s.UploadPart(context.Background(), j.Name, j.UploadId, j.Chunk.Number,
  452. &io.LimitedReader{R: fd, N: j.Chunk.Size}, j.Opt)
  453. res.PartNumber = j.Chunk.Number
  454. res.Resp = resp
  455. if err != nil {
  456. rt--
  457. if rt == 0 {
  458. fd.Close()
  459. results <- &res
  460. break
  461. }
  462. continue
  463. }
  464. fd.Close()
  465. results <- &res
  466. break
  467. }
  468. }
  469. }
  470. func DividePart(fileSize int64) (int64, int64) {
  471. partSize := int64(1 * 1024 * 1024)
  472. partNum := fileSize / partSize
  473. for partNum >= 10000 {
  474. partSize = partSize * 2
  475. partNum = fileSize / partSize
  476. }
  477. return partNum, partSize
  478. }
  479. func SplitFileIntoChunks(filePath string, partSize int64) ([]Chunk, int, error) {
  480. if filePath == "" {
  481. return nil, 0, errors.New("filePath invalid")
  482. }
  483. file, err := os.Open(filePath)
  484. if err != nil {
  485. return nil, 0, err
  486. }
  487. defer file.Close()
  488. stat, err := file.Stat()
  489. if err != nil {
  490. return nil, 0, err
  491. }
  492. var partNum int64
  493. if partSize > 0 {
  494. partSize = partSize * 1024 * 1024
  495. partNum = stat.Size() / partSize
  496. if partNum >= 10000 {
  497. return nil, 0, errors.New("Too many parts, out of 10000")
  498. }
  499. } else {
  500. partNum, partSize = DividePart(stat.Size())
  501. }
  502. var chunks []Chunk
  503. var chunk = Chunk{}
  504. for i := int64(0); i < partNum; i++ {
  505. chunk.Number = int(i + 1)
  506. chunk.OffSet = i * partSize
  507. chunk.Size = partSize
  508. chunks = append(chunks, chunk)
  509. }
  510. if stat.Size()%partSize > 0 {
  511. chunk.Number = len(chunks) + 1
  512. chunk.OffSet = int64(len(chunks)) * partSize
  513. chunk.Size = stat.Size() % partSize
  514. chunks = append(chunks, chunk)
  515. partNum++
  516. }
  517. return chunks, int(partNum), nil
  518. }
  519. // MultiUpload 为高级upload接口,并发分块上传
  520. // 注意该接口目前只供参考
  521. //
  522. // 当 partSize > 0 时,由调用者指定分块大小,否则由 SDK 自动切分,单位为MB
  523. // 由调用者指定分块大小时,请确认分块数量不超过10000
  524. //
  525. func (s *ObjectService) MultiUpload(ctx context.Context, name string, filepath string, opt *MultiUploadOptions) (*CompleteMultipartUploadResult, *Response, error) {
  526. // 1.Get the file chunk
  527. chunks, partNum, err := SplitFileIntoChunks(filepath, opt.PartSize)
  528. if err != nil {
  529. return nil, nil, err
  530. }
  531. // 2.Init
  532. optini := opt.OptIni
  533. res, _, err := s.InitiateMultipartUpload(ctx, name, optini)
  534. if err != nil {
  535. return nil, nil, err
  536. }
  537. uploadID := res.UploadID
  538. var poolSize int
  539. if opt.ThreadPoolSize > 0 {
  540. poolSize = opt.ThreadPoolSize
  541. } else {
  542. // Default is one
  543. poolSize = 1
  544. }
  545. chjobs := make(chan *Jobs, 100)
  546. chresults := make(chan *Results, 10000)
  547. optcom := &CompleteMultipartUploadOptions{}
  548. // 3.Start worker
  549. for w := 1; w <= poolSize; w++ {
  550. go worker(s, chjobs, chresults)
  551. }
  552. // 4.Push jobs
  553. for _, chunk := range chunks {
  554. partOpt := &ObjectUploadPartOptions{}
  555. if optini != nil && optini.ObjectPutHeaderOptions != nil {
  556. partOpt.XCosSSECustomerAglo = optini.XCosSSECustomerAglo
  557. partOpt.XCosSSECustomerKey = optini.XCosSSECustomerKey
  558. partOpt.XCosSSECustomerKeyMD5 = optini.XCosSSECustomerKeyMD5
  559. }
  560. job := &Jobs{
  561. Name: name,
  562. RetryTimes: 3,
  563. FilePath: filepath,
  564. UploadId: uploadID,
  565. Chunk: chunk,
  566. Opt: partOpt,
  567. }
  568. chjobs <- job
  569. }
  570. close(chjobs)
  571. // 5.Recv the resp etag to complete
  572. for i := 1; i <= partNum; i++ {
  573. res := <-chresults
  574. // Notice one part fail can not get the etag according.
  575. if res.Resp == nil {
  576. // Some part already fail, can not to get the header inside.
  577. return nil, nil, fmt.Errorf("UploadID %s, part %d failed to get resp content.", uploadID, res.PartNumber)
  578. }
  579. // Notice one part fail can not get the etag according.
  580. etag := res.Resp.Header.Get("ETag")
  581. optcom.Parts = append(optcom.Parts, Object{
  582. PartNumber: res.PartNumber, ETag: etag},
  583. )
  584. }
  585. sort.Sort(ObjectList(optcom.Parts))
  586. v, resp, err := s.CompleteMultipartUpload(context.Background(), name, uploadID, optcom)
  587. return v, resp, err
  588. }