Upload Callback (SDK for Go)
Function
You can specify the callback parameters in an object upload request. After the object is successfully uploaded, OBS calls back the upload result to a specific server and returns the callback result to you.
- If the callback succeeds, a result is returned to the client, with the ETag of the uploaded object returned as the header field. If the callback result also contains the ETag, the ETags will be combined and then returned.
- If the callback fails, status code 203 will be returned, indicating that the object is successfully uploaded but the callback fails. For more callback reasons, see How Do I Locate an Upload Callback Failure?.
Restrictions
- To upload an object, you must be the bucket owner or have the required permission (obs:object:PutObject in IAM or PutObject in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Configuring an Object Policy.
- The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
- If the size of an uploaded image exceeds 25 MB, the basic image information cannot be obtained using the magic variables related to imageInfo. As a result, the callback fails.
- To enable upload callbacks, you need to configure the SDK using the WithCallbackHeader method. This method is currently supported only for the APIs of streaming uploads, file-based uploads, and resumable uploads.
Method
WithCallbackHeader(callback string)
Request Parameters
| Parameter | Type | Mandatory (Yes/No) | Description |
|---|---|---|---|
| callback | string | Yes | Explanation: Upload callback policy Restrictions: The value must be a Base64-encoded JSON string. For details about the callback parameters included in the JSON string, see Table 2. Value range: None Default value: None |
| Parameter | Type | Mandatory (Yes/No) | Description |
|---|---|---|---|
| callbackUrl | string | Yes | Explanation: After an object is uploaded successfully, OBS sends a callback request to the URL using the POST method. Restrictions:
Value range: None Default value: None |
| callbackHost | string | No | Explanation: Value of the Host header in the callback request. Restrictions: None Value range: None Default value: None. The value of Host parsed from the callbackUrl parameter is used. |
| callbackBody | string | Yes | Explanation: Body of the callback request. Restrictions:
Value range: None Default value: None |
| callbackBodyType | string | No | Explanation: Value of the Content-Type header in the callback request. Restrictions: None Value range:
Default value: application/json |
| Variable | Type | Description |
|---|---|---|
| fname | string | Name of the original file to be uploaded |
| fsize | string | Size of the file, in bytes The name is compatible with size. |
| etag | string | Object ETag |
| bucket | string | Name of the bucket to which the object is uploaded |
| key | string | Explanation: The name of the uploaded object. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name. For example, if the address for accessing the object is examplebucket.obs.cn-north-4.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt. Value range: The value must contain 1 to 1,024 characters. Default value: None |
| ext | string | Extension of the file to be uploaded. It is automatically obtained from parameter mimeType or $(fname). The name is compatible with mimeType. |
| override | string | Whether the uploaded object overwrites an existing one. The value is true or false. If the name of the object to be uploaded already exists in the bucket, the existing object may be overwritten. true indicates that the existing object will be overwritten. false means the existing object will not be overwritten. When versioning is enabled for a bucket, override is always false. |
| imageInfo | string | Obtained basic information about the image to be uploaded. This parameter can be used only in the image uploading scenarios. This variable contains the $(imageInfo.width) and $(imageInfo.height) fields, which indicate the width and height of an image. NOTE: If the size of an uploaded image exceeds 25 MB, the basic image information cannot be obtained using the magic variables related to imageInfo. As a result, the callback fails. |
Responses
The responses follow the format of the original method's function call. For details, see Sample Code - Streaming Upload.
The following two methods are added to the response parameters:
1. ReadCallbackBody: This method allows you to read the response body returned by the callback server.
2. CloseCallbackBody: This method closes the response body returned by the callback server and must be called.
Sample Code - Streaming Upload
This example uses streaming to upload example/objectname to bucket examplebucket and specifies http://example.com:80 as the upload callback server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // Import the dependency package. import ( "fmt" "bytes" "encoding/base64" "encoding/json" "strings" obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" ) func main() { //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. //Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html. ak := os.Getenv("AccessKeyID") sk := os.Getenv("SecretAccessKey") // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are not advised to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. // securityToken := os.Getenv("SecurityToken") // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use. endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com" // Create an obsClient instance. // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance. obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/) input := &obs.PutObjectInput{} // Specify the bucket name. input.Bucket = "bucketname" // Specify the object (example/objectname as an example) to upload. input.Key = "objectname" input.Body = strings.NewReader("Hello OBS") callbackMap := map[string]string{} callbackMap["callbackUrl"] = "http://example.com:80" // callbackMap["callbackHost"] = "example.com" callbackMap["callbackBody"] = "filename=${object}&size=${size}&mimeType=${mimeType}" // callbackMap["callbackBodyType"] = "application/x-www-form-urlencoded" callbackBuffer := bytes.NewBuffer([]byte{}) callbackEncoder := json.NewEncoder(callbackBuffer) callbackEncoder.SetEscapeHTML(false) err := callbackEncoder.Encode(callbackMap) if err != nil { fmt.Print(err) return } callbackVal := base64.StdEncoding.EncodeToString(callbackBuffer.Bytes()) output, err := obsClient.PutObject(input, obs.WithCallbackHeader(callbackVal)) if err == nil { // This method must be invoked. defer output.CloseCallbackBody() fmt.Printf("RequestId:%s\n", output.RequestId) fmt.Printf("ETag:%s\n", output.ETag) p := make([]byte, 1024) var readErr error var readCount int // Read the callback content. for { readCount, readErr = output.ReadCallbackBody(p) if readCount > 0 { fmt.Printf("%s", p[:readCount]) } if readErr != nil { break } } } else if obsError, ok := err.(obs.ObsError); ok { fmt.Printf("Code:%s\n", obsError.Code) fmt.Printf("Message:%s\n", obsError.Message) } } |
Sample Code - Resumable Upload
This example uploads example/objectname to bucket examplebucket in a resumable upload and specifies http://example.com:80 as the upload callback server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | // Import the dependency package. import ( "fmt" "bytes" "encoding/base64" "encoding/json" "strings" obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" ) func main() { //Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage. //Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html. ak := os.Getenv("AccessKeyID") sk := os.Getenv("SecretAccessKey") // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are not advised to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. // securityToken := os.Getenv("SecurityToken") // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use. endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com" // Create an obsClient instance. // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance. obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/) input := &obs.UploadFileInput{} // Specify the bucket name. input.Bucket = "bucketname" // Specify the object (example/objectname as an example) to upload. input.Key = "objectname" // Specify your local file (/tmp/objectname as an example) to upload. input.UploadFile = "/tmp/objectname" // Specify whether to enable resumable upload (true as an example). The default value is false, indicating that resumable upload is disabled. input.EnableCheckpoint = true // Specify a part size, in bytes. This example sets each part to 9 MB. input.PartSize = 9 * 1024 * 1024 // Specify the maximum number of parts that can be concurrently uploaded. 5 is used as an example. input.TaskNum = 5 callbackMap := map[string]string{} callbackMap["callbackUrl"] = "http://example.com:80" // callbackMap["callbackHost"] = "example.com" callbackMap["callbackBody"] = "filename=${object}&size=${size}&mimeType=${mimeType}" // callbackMap["callbackBodyType"] = "application/x-www-form-urlencoded" callbackBuffer := bytes.NewBuffer([]byte{}) callbackEncoder := json.NewEncoder(callbackBuffer) callbackEncoder.SetEscapeHTML(false) err := callbackEncoder.Encode(callbackMap) if err != nil { fmt.Print(err) return } callbackVal := base64.StdEncoding.EncodeToString(callbackBuffer.Bytes()) output, err := obsClient.UploadFile(input, obs.WithCallbackHeader(callbackVal)) if err == nil { // This method must be invoked. defer output.CloseCallbackBody() fmt.Printf("RequestId:%s\n", output.RequestId) fmt.Printf("ETag:%s\n", output.ETag) p := make([]byte, 1024) var readErr error var readCount int // Read the callback content. for { readCount, readErr = output.ReadCallbackBody(p) if readCount > 0 { fmt.Printf("%s", p[:readCount]) } if readErr != nil { break } } } else if obsError, ok := err.(obs.ObsError); ok { fmt.Printf("Code:%s\n", obsError.Code) fmt.Printf("Message:%s\n", obsError.Message) } } |
Helpful Links
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot