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.

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