Authorizing a Third Party to Upload Objects
Scenarios
By default, only the bucket owner has read and write permissions for objects and can upload objects to the bucket. In some scenarios, third-party users need to upload objects to a bucket. If these users do not have the upload permission, you can grant temporary permissions to them for accessing OBS and uploading objects within a validity period. For example, some companies have user management systems that manage app users and local users. These users do not have IAM user permissions, so you can grant temporary permissions to allow these users to temporarily access OBS.
Use either of the following methods:
- Temporary security credentials
- A temporary URL
Important Notes
| Method | Description |
|---|---|
| Temporary security credentials | The validity period of temporary security credentials is from 15 minutes to 24 hours. |
| When obtaining temporary security credentials, you can use the policy parameter to define the least temporary permissions that can be granted to IAM users. | |
| Temporary URL | Only the bucket owner can grant a temporary URL to others. If the owner changes the validity period of a URL, OBS obtains the authentication information again to generate a new URL. |
| The obs:PutObject permission is required for uploading an object using a temporary URL. You need to create a custom policy that contains the obs:PutObject permission and then assign the permission to IAM users. |
Using Temporary Security Credentials to Grant Upload Permissions
You can assign temporary security credentials (including an AK, an SK, and a security token) to a third-party application or an IAM user, so that they can access OBS only for a specified period of time with defined permissions.
The temporary AK/SK and the security token comply with the least privilege principle. They must be used together to call an API for authentication and the x-obs-security-token field must be added to the request header.
For details, see Accessing OBS Using Temporary Access Keys.
Operation Process
The following describes the process of using temporary security credentials to grant other users permissions to upload files.
To comply with the principle of least privilege, you need to create an IAM user, grant permissions to the user, and attach a temporary policy when obtaining a temporary security credential to further restrict the permissions that can be granted to other users.
- If no temporary policy is configured, the obtained temporary security credential has the same permissions as the IAM user.
- If a temporary policy is configured, the permissions of the obtained temporary security credential are further restricted by the temporary policy in addition to the original permissions of the IAM user.
Operation Example
Assume that you want an IAM user (username: APPServer) to access the APPClient folder in the bucket hi-company and you want to request two different temporary security credentials to distribute to two client apps APP-1 and APP-2. APP-1 can upload files only to APPClient/APP-1, and APP-2 can upload files only to APPClient/APP-2.
- Create a custom policy.
Create a custom policy, and set action to obs:object:* and Resource to OBS:*:*:object:hi-company/APPClient/*. For details, see Creating a Custom Policy. The policy content is as follows:
{ "Version": "1.1", "Statement": [ { "Effect": "Allow", "Action": [ "obs:object:*" ], "Resource": [ "OBS:*:*:object:hi-company/APPClient/*" ] } ] } - Create an IAM user and grant permissions to the user.
Create an IAM user named APPServer and grant the user the permissions contained in the custom policy created in 1. For details, see Creating an IAM User and Assigning Permissions to an IAM User.
- (IAM user) Obtain temporary security credentials.
The IAM user (APPServer) obtains temporary security credentials (temporary AKs/SKs and security tokens) for APP-1 and APP-2. Temporary policies must be configured to further restrict the permissions that can be granted. For details, see Obtaining a Temporary AK/SK and Security Token.
The IAM user obtains a temporary security credential for APP-1 so that APP-1 can only upload files to APPClient/APP-1. The following is an example:
{ "auth": { "identity": { "policy": { "Version": "1.1", "Statement": [ { "Action": [ "obs:object:PutObject" ], "Resource": [ "obs:*:*:object:hi-company/APPClient/APP-1/*" ], "Effect": "Allow" } ] }, "token": { "duration-seconds": 900 }, "methods": [ "token" ] } } }The IAM user obtains a temporary security credential for APP-2 so that APP-2 can only upload files to APPClient/APP-2. The following is an example:
{ "auth": { "identity": { "policy": { "Version": "1.1", "Statement": [ { "Action": [ "obs:object:PutObject" ], "Resource": [ "obs:*:*:object:hi-company/APPClient/APP-2/*" ], "Effect": "Allow" } ] }, "token": { "duration-seconds": 900 }, "methods": [ "token" ] } } } - (Third-party user) Use the temporary security credential to access OBS resources.
After obtaining the temporary security credentials, APP-1 and APP-2 can use the OBS APIs or SDKs to access OBS. APP-1 can only upload files to APPClient/APP-1, and APP-2 can only upload files to APPClient/APP-2.
Using a Temporary URL to Grant Upload Permissions
ObsClient allows you to create a URL with Query parameters that carry authentication information by specifying the security credentials, request method, and request parameters. You can share this URL with other users for temporary access. You need to specify the validity period of the temporary URL to restrict the allowed access duration.
Temporary URLs allow third-party users to upload objects without security credentials or authorization. OBS stores the objects uploaded by third-party users in a specified bucket.
For details, see Accessing OBS Using a Temporary URL.
Operation Process
The following describes the process of using a temporary URL to grant other users permissions to upload files.
Uploading a File Using a Temporary URL
The following describes how to use a temporary URL to upload a single file using the PUT method in the OBS SDK.
The validity period of a URL is as follows:
- If you use a temporary key to call the SDK API, the value of expires ranges from 0 to 86400 seconds (24 hours).
- If you use a permanent key to call the SDK API, the value of expires ranges from 0 to 630720000 seconds (about 20 years).
This example uses HttpMethodEnum.PUT to upload object objectname to bucket examplebucket based on a signed URL. The validity period of the URL is 3,600 seconds.
For details, see Accessing OBS Using a Signed URL (SDK for Java).
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.HttpMethodEnum; import com.obs.services.model.TemporarySignatureRequest; import com.obs.services.model.TemporarySignatureResponse; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.util.HashMap; import java.util.Map; public class PutObject001 { public static void main(String[] args) { // Obtain an AK/SK pair using environment variables or import it using other external methods. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. String ak = System.getenv("ACCESS_KEY_ID"); String sk = System.getenv("SECRET_ACCESS_KEY_ID"); // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, avoid using hard coding, which may result in leakage. // Obtain an AK/SK pair and a security token using environment variables or import them in other ways. If you use a temporary security credential to call an API, uncomment the following line. // String securityToken = System.getenv("SECURITY_TOKEN"); // Enter the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com"; // Obtain an endpoint using environment variables or import it in other ways. //String endPoint = System.getenv("ENDPOINT"); // Create an ObsClient instance. // Use a permanent AK/SK pair to initialize the client. ObsClient obsClient = new ObsClient(ak, sk, endPoint); // Use a temporary AK/SK pair and security token to initialize the client. // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint); try { // Set the validity period of the URL to 3600 seconds. long expireSeconds = 3600L; Map<String, String> headers = new HashMap<>(); String contentType = "text/plain"; headers.put("Content-Type", contentType); TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.PUT, expireSeconds); request.setBucketName("examplebucket"); request.setObjectKey("objectname"); request.setHeaders(headers); TemporarySignatureResponse response = obsClient.createTemporarySignature(request); System.out.println("Creating object using temporary signature url:"); System.out.println("\t" + response.getSignedUrl()); Request.Builder builder = new Request.Builder(); for (Map.Entry<String, String> entry : response.getActualSignedRequestHeaders().entrySet()) { builder.header(entry.getKey(), entry.getValue()); } // Make a PUT request to upload an object. Request httpRequest = builder.url(response.getSignedUrl()) .put(RequestBody.create(MediaType.parse(contentType), "Hello OBS".getBytes("UTF-8"))) .build(); OkHttpClient httpClient = new OkHttpClient.Builder() .followRedirects(false) .retryOnConnectionFailure(false) .cache(null) .build(); Call c = httpClient.newCall(httpRequest); Response res = c.execute(); System.out.println("Status:" + res.code()); if (res.body() != null) { System.out.println("Content:" + res.body().string() + "\n"); } res.close(); System.out.println("PutObject successfully"); } catch (ObsException e) { System.out.println("PutObject failed"); // Request failed. Print the HTTP status code. System.out.println("HTTP Code:" + e.getResponseCode()); // Request failed. Print the server-side error code. System.out.println("Error Code:" + e.getErrorCode()); // Request failed. Print the error message. System.out.println("Error Message:" + e.getErrorMessage()); // Request failed. Print the request ID. System.out.println("Request ID:" + e.getErrorRequestId()); System.out.println("Host ID:" + e.getErrorHostId()); e.printStackTrace(); } catch (Exception e) { System.out.println("PutObject failed"); // Print other error information. e.printStackTrace(); } } } |
The following is an example of generating a temporary URL for uploading an object. For details, see Creating a Signed URL (SDK for Python).
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 | import os import traceback import base64 from obs import ObsClient # Obtain an AK/SK pair using environment variables (recommended) or import it 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') # If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. # security_token = os.getenv('SecurityToken') # Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. server = '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, you must specify security_token when creating an instance. obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server) try: # Create a signed URL for uploading an object. res2 = obs_client.createSignedUrl(method='PUT', bucketName='bucketname', objectKey='objectkey', expires=3600, headers = {'Content-Type': 'text/plain'}) print('signedUrl:', res2['signedUrl']) print('actualSignedRequestHeaders:', res2['actualSignedRequestHeaders']) except Exception: print(traceback.format_exc()) |
The following is an example of generating a temporary URL for uploading an object. For details, see Creating a Signed URL (SDK for Go).
package main
import (
"fmt"
"net/http"
obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
"os"
"strings"
)
func main() {
// Obtain an AK/SK pair using environment variables or import an 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 of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one 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)*/)
if err != nil {
fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
}
putObjectInput := &obs.CreateSignedUrlInput{}
putObjectInput.Method = obs.HttpMethodPut
putObjectInput.Bucket = "examplebucket"
putObjectInput.Key = "example/objectname"
putObjectInput.Expires = 3600
// Create a signed URL for uploading an object.
putObjectOutput, err := obsClient.CreateSignedUrl(putObjectInput)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("SignedUrl:%s\n", putObjectOutput.SignedUrl)
fmt.Printf("ActualSignedRequestHeaders:%v\n", putObjectOutput.ActualSignedRequestHeaders)
// Call the signed URL.
payload := strings.NewReader("hello OBS!")
req, err := http.NewRequest("PUT", putObjectOutput.SignedUrl, payload)
req.Header = putObjectOutput.ActualSignedRequestHeaders
if err != nil {
fmt.Printf("Create request error, errMsg: %s", err.Error())
return
}
response, err := http.DefaultClient.Do(req)
if err == nil {
fmt.Printf("Use signed-url successful!\n")
fmt.Printf("Status:%s,Etag:%s\n", response.Status, response.Header.Get("Etag"))
return
}
fmt.Printf("Use signed-url successful!\n")
fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
fmt.Println(err)
} The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Authorized Access (BrowserJS SDK).
// Create an ObsClient instance.
var obsClient = new ObsClient({
// Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK before storing them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables. Before running the code in this example, configure environment variables AccessKeyID and SecretAccessKey.
// The front-end code does not have the process environment variable, so you need to use a module bundler like webpack to define the process variable.
// 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. access_key_id: process.env.AccessKeyID,
secret_access_key: process.env.SecretAccessKey,
// CN-Hong Kong is used as an example. Replace it with the one currently in use.
server: 'https://obs.ap-southeast-1.myhuaweicloud.com'
});
// Make a PUT request to upload an object.
var bucketName = 'bucketname';
var objectKey = 'objectname';
var method = 'PUT';
var headers = {
'Content-Type' : 'text/plain'
}
var res = obsClient.createSignedUrlSync({
Method : method,
Bucket : bucketName,
Key : objectKey,
Expires : 3600,
Headers : headers
});
var content = 'Hello OBS';
var reopt = {
method : method,
url : res.SignedUrl,
withCredentials: false,
headers : res.ActualSignedRequestHeaders || {},
validateStatus: function(status){
return status >= 200;
},
maxRedirects : 0,
responseType : 'text',
data : content,
};
axios.request(reopt).then(function (response) {
if(response.status < 300){
console.log('Creating object using temporary signature succeed.');
}else{
console.log('Creating object using temporary signature failed!');
console.log('status:' + response.status);
console.log('\n');
}
console.log(response.data);
console.log('\n');
}).catch(function (err) {
console.log('Creating object using temporary signature failed!');
console.log(err);
console.log('\n');
}); The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Authorized Access (.NET SDK).
// Initialize configuration parameters.
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK before storing them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables. Before running the code in this example, configure environment variables AccessKeyID and SecretAccessKey.
// 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.
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// Create an ObsClient instance.
ObsClient client = new ObsClient(accessKey, secretKey, config);
// Set the validity period of the URL to 3600 seconds.
long exipreSeconds = 3600;
CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.ObjectKey = "objectkey";
request.Method = HttpVerb.PUT;
request.Expires = exipreSeconds;
CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Creating object using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);
// Make a PUT request to upload an object.
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "PUT";
foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
{
webRequest.Headers.Add(header.Key, header.Value);
}
}
webRequest.SendChunked = true;
webRequest.AllowWriteStreamBuffering = false;
using (Stream requestStream = webRequest.GetRequestStream())
{
byte[] buffer = Encoding.UTF8.GetBytes("Hello OBS");
requestStream.Write(buffer, 0, buffer.Length);
}
HttpWebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
using (Stream stream = webResponse.GetResponseStream())
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine("Response Content:");
Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
} The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Authorized Access (Android SDK).
// Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running the code in this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID.
// 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.
String ak = System.getenv("ACCESS_KEY_ID");
String sk = System.getenv("SECRET_ACCESS_KEY_ID");
String endPoint = "https://your-endpoint";
// Create an ObsClient instance.
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
// Set the validity period of the URL to 3600 seconds.
long expireSeconds = 3600L;
Map<String, String> headers = new HashMap<String, String>();
String contentType = "text/plain";
headers.put("Content-Type", contentType);
TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.PUT, expireSeconds);
request.setBucketName("bucketname");
request.setObjectKey("objectname");
request.setHeaders(headers);
TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
Log.i("CreateTemporarySignature", "Creating object using temporary signature url:");
Log.i("CreateTemporarySignature", "\t" + response.getSignedUrl());
Request.Builder builder = new Request.Builder();
for (Map.Entry<String, String> entry : response.getActualSignedRequestHeaders().entrySet()) {
builder.header(entry.getKey(), entry.getValue());
}
// Make a PUT request to upload an object.
Request httpRequest = builder.url(response.getSignedUrl()).put(RequestBody.create(MediaType.parse(contentType), "Hello OBS".getBytes("UTF-8"))).build();
OkHttpClient httpClient = new OkHttpClient.Builder().followRedirects(false).retryOnConnectionFailure(false)
.cache(null).build();
Call c = httpClient.newCall(httpRequest);
Response res = c.execute();
Log.i("CreateTemporarySignature", "\tStatus:" + res.code());
if (res.body() != null) {
Log.i("CreateTemporarySignature", "\tContent:" + res.body().string() + "\n");
}
res.close(); The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Authorized Access (Java SDK).
static OBSClient *client;
NSString *endPoint = @"your-endpoint";
// Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK before storing them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables. Before running the code in this example, configure environment variables AccessKeyID and SecretAccessKey.
// 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.
char* ak_env = getenv("AccessKeyID");
char* sk_env = getenv("SecretAccessKey");
NSString *AK = [NSString stringWithUTF8String:ak_env ?: ""];
NSString *SK = [NSString stringWithUTF8String:sk_env ?: ""];
// Initialize identity authentication.
OBSStaticCredentialProvider *credentialProvider = [[OBSStaticCredentialProvider alloc] initWithAccessKey:AK secretKey:SK];
// Initialize service configuration.
OBSServiceConfiguration *conf = [[OBSServiceConfiguration alloc] initWithURLString:endPoint credentialProvider:credentialProvider];
// Initialize the client.
client = [[OBSClient alloc] initWithConfiguration:conf];
OBSPutObjectWithFileRequest *request = [[OBSPutObjectWithFileRequest alloc] initWithBucketName:@"bucketname"];
// Create a V2 authorized access URL.
[client createV2PreSignedURL:request expireAfter:3600 completionHandler:^(NSString *urlString, NSString *httpVerb, NSDictionary *signedHeaders) {
NSLog(@"%@",urlString);
}] The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Authorized Access (Java SDK).
// Import the dependency library.
require 'vendor/autoload.php';
// Import the SDK code library during the installation with source code.
// require 'obs-autoloader.php';
// Declare the namespace.
use Obs\ObsClient;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
// Create an ObsClient instance.
$obsClient = new ObsClient( [
// Obtain an AK/SK pair using environment variables (recommended) or import an 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. 'key' => getenv('ACCESS_KEY_ID'),
'secret' => getenv('SECRET_ACCESS_KEY'),
'endpoint' => 'https://your-endpoint'
'signature' => 'obs'
] );
// Set the validity period of the URL to 3600 seconds.
$expires = 3600;
// Upload an object.
$resp = $obsClient->createSignedUrl( [
'Method' => 'PUT',
'Bucket' => 'bucketname',
'Key' => 'objectname',
'Expires' => $expires
] );
printf("SignedUrl:%s\n", $resp ['SignedUrl']);
$url = $resp['SignedUrl'];
$httpClient = new Client(['verify' => false ]);
$content = 'Hello OBS';
try{
$response = $httpClient -> request('PUT', $url, ['body' => $content, 'headers'=> $resp['ActualSignedRequestHeaders']]);
printf("%s using temporary signature url:\n", 'Put object');
printf("\t%s successfully.\n", $url);
printf("\tStatus:%d\n", $response -> getStatusCode());
printf("\tContent:%s\n", $response -> getBody() -> getContents());
$response -> getBody()-> close();
}catch (ClientException $ex){
printf("%s using temporary signature url:\n", 'Put object');
printf("\t%s failed!\n", $url);
printf('Exception message:%s', $ex ->getMessage());
} The following is an example of generating a temporary URL for uploading an object. For details, see Using a Temporary URL for Access (Node.js SDK).
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 75 76 77 78 79 80 81 82 83 84 | // Import the OBS library. // Use npm for installation. const ObsClient = require("esdk-obs-nodejs"); // Use the source code for installation. // var ObsClient = require('./lib/obs'); // Create an ObsClient instance. const obsClient = new ObsClient({ // Obtain an AK/SK pair using environment variables (recommended) or import it 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. access_key_id: process.env.ACCESS_KEY_ID, secret_access_key: process.env.SECRET_ACCESS_KEY, // (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. // security_token: process.env.SECURITY_TOKEN, // Enter the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. server: "https://obs.ap-southeast-1.myhuaweicloud.com" }); function createSignedUrlSync() { // Specify the HTTP method. PUT is used in this example. const method = 'PUT'; const params = { // Specify a bucket name. Bucket: "examplebucket", // Specify an object (example/objectname in this example). Key: "example/objectname", // Specify the HTTP method. Method: method, // Specify the validity period of the signed URL, in seconds (3600 in this example). Expires: 3600, // Specify the headers that must be carried in the request. Headers: { "Content-Type": "text/plain", } }; // Create a signed URL for uploading an object. const res = obsClient.createSignedUrlSync(params); console.log("SignedUrl: %s", res.SignedUrl); console.log("ActualSignedRequestHeaders: %v", res.ActualSignedRequestHeaders); let content = 'Hello OBS'; // Make a PUT request to upload an object. var url = urlLib.parse(res.SignedUrl); var req = https.request({ method: method, host: url.hostname, port: url.port, path: url.path, rejectUnauthorized: false, headers: res.ActualSignedRequestHeaders || {} }); console.log('Creating object using url:' + res.SignedUrl); req.on('response', (serverback) => { var buffers = []; serverback.on('data', (data) => { buffers.push(data); }).on('end', () => { if (serverback.statusCode < 300) { console.log('Creating object using temporary signature succeed.'); } else { console.log('Creating object using temporary signature failed!'); console.log('status:' + serverback.statusCode); console.log('\n'); }; buffers = Buffer.concat(buffers); if (buffers.length > 0) { console.log(buffers.toString()); }; console.log('\n'); }); }).on('error', (err) => { console.log('Creating object using temporary signature failed!'); console.log(err); console.log('\n'); }); if (content) { req.write(content); }; req.end(); }; createSignedUrlSync(); |
Uploading a File in Multipart Mode Using a Temporary URL
If a large file fails to be uploaded to a bucket due to the client's inability to integrate the OBS SDK or poor network conditions, this file can be uploaded in multipart mode. The server initializes a multipart upload task and generates a temporary URL for each part. Then, the third-party uploads the parts, and the server then combines the parts into a complete file. The following is the sample code for using the SDK:
- The client initiates a file upload request.
The client sends a file upload request to the server, specifying the file name, file size, and expected part size (not greater than 5 GB).
Example:
curl -X POST https://example.com/uploadfile \ -H "Content-Type: application/json" \ -d '{ "fileName": "testexample.jpg", "fileSize": 104857600, "partSize": 5242880 }'
- The server:
- Calls the initiateMultipartUpload API to initialize the multipart upload task and obtain the globally unique identifier (upload ID) created by OBS, which is used to identify the multipart upload task.
- Calculates the number of parts based on the file size and expected part size.
- Generates a temporary URL for each part.
- Returns the list of temporary URLs.
The following is the sample code for initializing a multipart upload task and generating a temporary URL for each part:
import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.model.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class ObsExample { // Obtain the AK/SK pair using environment variables. Hard coding may cause leakage risks. // Obtain an AK/SK pair on the management console. static String ak = System.getenv("AccessKeyID"); static String sk = System.getenv("SecretAccessKey"); // If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. // static String securityToken = System.getenv("SecurityToken"); // Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. static String server = "https://obs.ap-southeast-1.myhuaweicloud.com"; static final int TOTAL_PARTS = 3; // Specify the number of parts to be uploaded. static final long EXPIRE_TIME = 3600; // Specify the validity period of the pre-signed URL, in seconds. public static void initMultipartUploadAndGenerateUrls() throws Exception { ObsClient obsClient = new ObsClient(ak, sk, server); try { InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest("bucket01", "objectkey"); InitiateMultipartUploadResult initResult = obsClient.initiateMultipartUpload(initRequest); String uploadId = initResult.getUploadId(); List<Map<String, Object>> parts = new ArrayList<>(); for (int partNumber = 1; partNumber <= TOTAL_PARTS; partNumber++) { Map<String, Object> queryParams = new HashMap<>(); queryParams.put("partNumber", String.valueOf(partNumber)); queryParams.put("uploadId", uploadId); TemporarySignatureRequest sigRequest = new TemporarySignatureRequest(HttpMethodEnum.PUT, EXPIRE_TIME); sigRequest.setBucketName("bucket01"); sigRequest.setObjectKey("objectkey"); sigRequest.setQueryParams(queryParams); TemporarySignatureResponse sigResponse = obsClient.createTemporarySignature(sigRequest); Map<String, Object> partInfo = new HashMap<>(); partInfo.put("part_number", partNumber); partInfo.put("url", sigResponse.getSignedUrl()); partInfo.put("method", "PUT"); parts.add(partInfo); } System.out.println("upload_id: " + uploadId); System.out.println("parts:"); for (Map<String, Object> part : parts) { System.out.println(" part_number: " + part.get("part_number")); System.out.println(" url: " + part.get("url")); System.out.println(" method: " + part.get("method")); } } finally { obsClient.close(); } } } - The client uploads parts.
The client uses the temporary URL of each part returned by the server to upload the parts in PUT mode. Sample code:
import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.model.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class ObsExample { // Obtain the AK/SK pair using environment variables. Hard coding may cause leakage risks. // Obtain an AK/SK pair on the management console. static String ak = System.getenv("AccessKeyID"); static String sk = System.getenv("SecretAccessKey"); // If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. // static String securityToken = System.getenv("SecurityToken"); // Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. static String server = "https://obs.ap-southeast-1.myhuaweicloud.com"; static final int TOTAL_PARTS = 3; // Specify the number of parts to be uploaded. static final long EXPIRE_TIME = 3600; // Specify the validity period of the pre-signed URL, in seconds. public static String uploadPart(String url, byte[] content) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", ""); connection.getOutputStream().write(content); connection.getOutputStream().flush(); int statusCode = connection.getResponseCode(); String etag = connection.getHeaderField("etag"); connection.disconnect(); if (statusCode != 200) { throw new RuntimeException("Upload part failed with status: " + statusCode); } return etag; } public static void uploadParts() throws Exception { try { List<String> etagList = new ArrayList<>(); String url = "..."; // Specify the URL generated by the server. byte[][] contents = {"...". getBytes(), "...". getBytes()}; // Specify the content to be uploaded by the client. for (byte[] content : contents) { String etag = uploadPart(url, content); etagList.add(etag); } System.out.println("etag list:"); for (String etag : etagList) { System.out.println(" " + etag); } } catch (Exception e) { e.printStackTrace(); } } }
You can also use the curl command to send a request and use the temporary URL of each part returned by the server to upload the part in PUT mode.
curl -X PUT -T <local_file_path> -s '<url>' -kvs
- The server combines the parts.
The server combines uploaded parts into a complete file after the client notifies it of upload completion, then returns the result to the client.
import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.model.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class ObsExample { // Obtain the AK/SK pair using environment variables. Hard coding may cause leakage risks. // Obtain an AK/SK pair on the management console. static String ak = System.getenv("AccessKeyID"); static String sk = System.getenv("SecretAccessKey"); // If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. // static String securityToken = System.getenv("SecurityToken"); // Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. static String server = "https://obs.ap-southeast-1.myhuaweicloud.com"; static final int TOTAL_PARTS = 3; // Specify the number of parts to be uploaded. static final long EXPIRE_TIME = 3600; // Specify the validity period of the pre-signed URL, in seconds. public static void completeMultipartUpload(String uploadId) throws Exception { ObsClient obsClient = new ObsClient(ak, sk, server); try { String[] etags = {"xxxxxx", "xxxxxx", "xxxxxx"}; // This is the response returned after the client uploads parts. The parts must be arranged in sequence. CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest("bucket01", "objectkey", uploadId); for (int i = 0; i < etags.length; i++) { CompletePart part = new CompletePart(); part.setPartNumber(i + 1); part.setEtag(etags[i]); completeRequest.addPart(part); } CompleteMultipartUploadResult result = obsClient.completeMultipartUpload(completeRequest); if (result.getStatusCode() == 200) { System.out.println("UploadPart successfully"); } } catch (Exception e) { e.printStackTrace(); } finally { obsClient.close(); } } }
- The client initiates a file upload request.
The client sends a file upload request to the server, specifying the file name, file size, and expected part size (not greater than 5 GB).
Example:
curl -X POST https://example.com/uploadfile \ -H "Content-Type: application/json" \ -d '{ "fileName": "testexample.jpg", "fileSize": 104857600, "partSize": 5242880 }'
- The server:
- Calls the initiateMultipartUpload API to initialize the multipart upload task and obtain the globally unique identifier (upload ID) created by OBS, which is used to identify the multipart upload task.
- Calculates the number of parts based on the file size and expected part size.
- Generates a temporary URL for each part.
- Returns the list of temporary URLs.
The following is the sample code for initializing a multipart upload task and generating a temporary URL for each part:
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback import json from obs import ObsClient from obs import CompleteMultipartUploadRequest, CompletePart # Obtain an AK/SK pair using environment variables (recommended) or import it 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') # If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. # security_token = os.getenv('SecurityToken') # Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. server = 'https://obs.ap-southeast-1.myhuaweicloud.com' TOTAL_PARTS = 3 # Specify the number of parts to be uploaded. EXPIRE_TIME = 3600 # Specify the validity period of the pre-signed URL, in seconds. # Create an ObsClient instance. # If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance. obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server) try: resp = obs_client.initiateMultipartUpload(bucketName='bucket01', objectKey='objectkey') upload_id = resp.body.uploadId parts = [] # Generate a part URL. local_file_path = "/your_local_file_path" for part_number in range(1, TOTAL_PARTS + 1): resp2 = obs_client.createSignedUrl(method='PUT', bucketName='bucket01', objectKey='objectkey', queryParams = {"partNumber": part_number, "uploadId": upload_id}, expires=EXPIRE_TIME) parts.append({ "part_number": part_number, "url": resp2['signedUrl'], "method": "PUT", }) output = { "upload_id": upload_id, "parts": parts } print(json.dumps(output, indent=2)) - The client uploads parts.
The client uses the temporary URL of each part returned by the server to upload the parts in PUT mode. Sample code:
import traceback import urllib.request def upload_part(url, content): # Python 3's request supports the method parameter. headers = {"Content-type": ""} request = urllib.request.Request(url, data=content, headers=headers, method="PUT") # Send the request and obtain a response. with urllib.request.urlopen(request) as response: status_code = response.getcode() # Obtain the ETag from the response header. (The HTTP header is case insensitive. Using .get() is more secure.) etag = response.headers.get('ETag') or response.headers.get('etag') return status_code, etag TOTAL_PARTS = 3 # Specify the number of parts to be uploaded. try: etag_list = [] url = ".." # Specify the URL generated by the server. # Note: If the content to be uploaded is a string, you need to encode it into bytes first (for example, b"..."). contents = [b"...", b"...."] # Specify the content to be uploaded by the client. for content in contents: status_code, etag = upload_part(url, content) etag_list.append(etag) print("etag list:") print(etag_list) except Exception: print(traceback.format_exc())
You can also use the curl command to send a request and use the temporary URL of each part returned by the server to upload the part in PUT mode.
curl -X PUT -T <local_file_path> -s '<url>' -kvs
- The server combines the parts.
The server combines uploaded parts into a complete file after the client notifies it of upload completion, then returns the result to the client.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback import json from obs import ObsClient from obs import CompleteMultipartUploadRequest, CompletePart # Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage. # Obtain an AK/SK pair on the management console. # For details about how to obtain the AK/SK, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html. ak = os.getenv('AccessKeyID') sk = os.getenv('SecretAccessKey') # If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. # security_token = os.getenv('SecurityToken') # Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. server = 'https://obs.ap-southeast-1.myhuaweicloud.com' TOTAL_PARTS = 3 # Specify the number of parts to be uploaded. EXPIRE_TIME = 3600 # Specify the validity period of the pre-signed URL, in seconds. # Create an ObsClient instance. # If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance. obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server) try: # Combine parts. etags = ["xxxxxx","xxxxxx","xxxxxx"] # This is the response returned after the client uploads parts. The parts must be arranged in sequence. upload_request = CompleteMultipartUploadRequest() for i, etag in enumerate(etags): upload_request.add_part(CompletePart(i + 1, etag)) resp = obs_client.completeMultipartUpload(bucketName='bucket01', objectKey='objectkey', uploadId=upload_id, completeMultipartUploadRequest=upload_request) if (resp['status'] == 200): print("UploadPart successfully") except Exception: print(traceback.format_exc())
Setting an Upload Callback
You can set callback parameters in an object upload request. After the object upload succeeds, OBS sends the callback result to your specified server and returns the callback response to you. For details about the callback, see Upload Callback (SDK for Go).
The core difference between uploading with the callback and common upload is that the x-obs-callback header is included in the signature calculation.
- The file owner generates a temporary access URL with the PUT method that carries the upload callback parameter.
import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.model.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class ObsExample { // Obtain the AK/SK pair using environment variables. Hard coding may cause leakage risks. // Obtain an AK/SK pair on the management console. static String ak = System.getenv("AccessKeyID"); static String sk = System.getenv("SecretAccessKey"); // If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. // static String securityToken = System.getenv("SecurityToken"); // Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. static String server = "https://obs.ap-southeast-1.myhuaweicloud.com"; public static String buildCallbackHeaderValue(String callbackUrl, String callbackBody, String callbackBodyType) throws Exception { String callbackPolicy = String.format( "{\"callbackUrl\":\"%s\",\"callbackBody\":\"%s\",\"callbackBodyType\":\"%s\"}", callbackUrl, callbackBody, callbackBodyType ); return Base64.getEncoder().encodeToString(callbackPolicy.getBytes("UTF-8")); } static final long EXPIRE_TIME = 3600; // Specify the validity period of the pre-signed URL, in seconds. public static void generateUploadUrlWithCallback() throws Exception { ObsClient obsClient = new ObsClient(ak, sk, server); try { String callbackUrl = "http://callback"; // Specify the address of the callback server. The address must be accessible from the Internet. String callbackBody = "{\"key\":\"${object}\",\"etag\":\"${etag}\",\"size\":\"${size}\",\"bucket\":\"${bucket}\"}"; String callbackHeaderValue = buildCallbackHeaderValue(callbackUrl, callbackBody, "application/json"); Map<String, Object> headers = new HashMap<>(); headers.put("Content-Type", "text/plain"); headers.put("x-obs-callback", callbackHeaderValue); TemporarySignatureRequest sigRequest = new TemporarySignatureRequest(HttpMethodEnum.PUT, EXPIRE_TIME); sigRequest.setBucketName("bucketname"); sigRequest.setObjectKey("objectkey"); sigRequest.setHeaders(headers); TemporarySignatureResponse sigResponse = obsClient.createTemporarySignatureUrl(sigRequest); System.out.println("signedUrl: " + sigResponse.getSignedUrl()); System.out.println("actualSignedRequestHeaders: " + sigResponse.getActualSignedRequestHeaders()); } catch (Exception e) { e.printStackTrace(); } finally { obsClient.close(); } } } - A third-party user uses the temporary URL with the PUT method to upload a file.
import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.model.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; public class ObsExample { // Obtain the AK/SK pair using environment variables. Hard coding may cause leakage risks. // Obtain an AK/SK pair on the management console. static String ak = System.getenv("AccessKeyID"); static String sk = System.getenv("SecretAccessKey"); // If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. // static String securityToken = System.getenv("SecurityToken"); // Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. static String server = "https://obs.ap-southeast-1.myhuaweicloud.com"; public static void uploadWithCallback(String presignedUrl, String callbackHeaderValue, byte[] content, String contentType) throws Exception { HttpURLConnection connection = (HttpURLConnection) new URL(presignedUrl).openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("x-obs-callback", callbackHeaderValue); connection.setRequestProperty("Content-Length", String.valueOf(content.length)); connection.getOutputStream().write(content); connection.getOutputStream().flush(); int statusCode = connection.getResponseCode(); Map<String, List<String>> responseHeaders = connection.getHeaderFields(); StringBuilder responseBody = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { responseBody.append(line); } } connection.disconnect(); System.out.println("\nResponse result"); System.out.println(" HTTP Status: " + statusCode); } public static void main(String[] args) throws Exception { // Upload the file using a URL. uploadWithCallback("presignedUrl", "callbackHeaderValue", "content".getBytes(), "text/plain"); } }
- The file owner generates a temporary access URL with the PUT method that carries the upload callback parameter.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback import base64 from obs import ObsClient import json # Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage. # Obtain an AK/SK pair on the management console. # For details about how to obtain the AK/SK, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html. ak = os.getenv('AccessKeyID') sk = os.getenv('SecretAccessKey') # If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables. # security_token = os.getenv('SecurityToken') # Set server to the endpoint of the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one in use. server = 'https://obs.ap-southeast-1.myhuaweicloud.com' def build_callback_header_value(callback_url, callback_body, callback_body_type): callback_policy = { "callbackUrl": callback_url, "callbackBody": callback_body, "callbackBodyType": callback_body_type } callback_json = json.dumps(callback_policy) callback_base64 = base64.b64encode(callback_json) return callback_base64 CALLBACK_URL = "http://callback" # Specify the address of the callback server. The address must be accessible from the Internet. callback_body = json.dumps({ "key": "${object}", "etag": "${etag}", "size": "${size}", "bucket": "${bucket}" }) callback_header_value = build_callback_header_value( callback_url=CALLBACK_URL, callback_body=callback_body, callback_body_type="application/json" ) # Create an ObsClient instance. # If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance. obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server) try: # Create a signed URL for uploading an object. res2 = obs_client.createSignedUrl(method='PUT', bucketName='bucketname', objectKey='objectkey', expires=3600, headers = {'Content-Type': 'text/plain', "x-obs-callback": callback_header_value}) print('signedUrl:', res2['signedUrl']) print('actualSignedRequestHeaders:', res2['actualSignedRequestHeaders']) except Exception: print(traceback.format_exc()) - A third-party user uses the temporary URL with the PUT method to upload a file.
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib.request import base64 import json UPLOAD_CONTENT = 'upload content' CONTENT_TYPE = 'text/plain' def build_callback_header_value(callback_url, callback_body, callback_body_type): callback_policy = { "callbackUrl": callback_url, "callbackBody": callback_body, "callbackBodyType": callback_body_type } callback_json = json.dumps(callback_policy) callback_base64 = base64.b64encode(callback_json) return callback_base64 def upload_with_callback(presigned_url, callback_header_value, content, content_type): # Construct the request header. headers = { "Content-Type": content_type, "x-obs-callback": callback_header_value, "Content-Length": str(len(content)), } # Use Python 3's urllib.request.Request to directly set method to PUT. request = urllib.request.Request(presigned_url, data=content, headers=headers, method="PUT") # Send the request and obtain a response. with urllib.request.urlopen(request) as response: status_code = response.getcode() response_headers = dict(response.info()) response_body = response.read() return status_code, response_headers, response_body if __name__ == '__main__': CALLBACK_URL = "http://callback" # Specify the address of the callback server. The address must be accessible from the Internet. callback_body = json.dumps({ "key": "${object}", "etag": "${etag}", "size": "${size}", "bucket": "${bucket}" }) callback_header_value = build_callback_header_value( callback_url=CALLBACK_URL, callback_body=callback_body, callback_body_type="application/json" ) presigned_url = 'https://bucketname.obs.cn-north-4.myhuaweicloud.com/objectkey?Expires=1789872566&Signature=at2xDy2Ys0X16Z9vz0cm0yTLymE%3D&AccessKeyId=XXXX' # The file owner generates a temporary access URL with the PUT method that carries the upload callback parameter. status_code, resp_headers, resp_body = upload_with_callback( presigned_url=presigned_url, callback_header_value=callback_header_value, content=UPLOAD_CONTENT, content_type=CONTENT_TYPE ) print("\nResponse result") print(" HTTP Status: %s" % str(status_code))
You can also use the curl command to send a request and use the temporary URL with the PUT method to upload a file.
curl -X PUT -T '<File to be uploaded>' -H 'x-obs-callback:callback_value' -H 'Content-Type:text/plain' -s '<Generated URL>' -kvs
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