En cas d'instabilité du réseau ou d'exceptions logicielles, le transfert vers Object Storage Service (OSS) d'un objet volumineux (supérieur à 5 Go) peut échouer. Parfois, plusieurs tentatives restent infructueuses. Utilisez alors le téléchargement avec reprise. Cette méthode divise l'objet en plusieurs parties et les transfère en parallèle pour accélérer l'opération. Un fichier de point de contrôle (checkpoint) enregistre la progression. Si une partie échoue, le transfert reprend exactement là où il s'était arrêté, selon les informations contenues dans ce fichier. Une fois toutes les parties transférées, elles sont assemblées pour former l'objet complet.
Prérequis
Un bucket doit exister. Pour plus d'informations, consultez la rubrique Créer un bucket.
Notes d'utilisation
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, privilégiez un endpoint interne. La liste des régions et endpoints pris en charge figure dans la documentation Régions et endpoints.
L'utilisation du téléchargement avec reprise nécessite l'autorisation
oss:PutObject. Pour attribuer cette permission via une politique personnalisée, reportez-vous à la section Accorder une politique personnalisée.Le fichier de point de contrôle enregistre la progression du transfert. Assurez-vous de disposer des droits d'écriture sur ce fichier.
Ce fichier contient une somme de contrôle (checksum) immuable. Toute corruption du fichier de point de contrôle vous obligera à relancer le transfert de l'intégralité des parties de l'objet.
Si le fichier local est modifié pendant le transfert, vous devez reprendre le téléchargement de toutes les parties depuis le début.
Utiliser les SDK OSS
Les extraits de code ci-dessous illustrent la mise en œuvre du téléchargement avec reprise via les SDK OSS pour les langages de programmation courants. Pour découvrir comment procéder avec d'autres langages, consultez la page Présentation.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class UploadFile {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
ObjectMetadata meta = new ObjectMetadata();
// Specify the type of content that you want to upload.
// meta.setContentType("text/plain");
// Specify the access control list (ACL) of the object that you want to upload.
// meta.setObjectAcl(CannedAccessControlList.Private);
// Configure multiple parameters by using UploadFileRequest.
// Specify the name of the bucket such as examplebucket and the full path of the object such as exampledir/exampleobject.txt. Do not include the bucket name in the full path.
UploadFileRequest uploadFileRequest = new UploadFileRequest("examplebucket","exampledir/exampleobject.txt");
// Configure a single parameter by using UploadFileRequest.
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs.
uploadFileRequest.setUploadFile("D:\\localpath\\examplefile.txt");
// Specify the number of concurrent threads for the upload task. Default value: 1.
uploadFileRequest.setTaskNum(5);
// Specify the part size. Unit: bytes. Valid values: 100 KB to 5 GB. Default value: 100 KB.
uploadFileRequest.setPartSize(1 * 1024 * 1024);
// Specify whether to enable resumable upload. By default, resumable upload is disabled.
uploadFileRequest.setEnableCheckpoint(true);
// Specify the checkpoint file that records the upload progress of each part. This checkpoint file stores information about the upload progress. If a part fails to be uploaded, the task can be continued based on the progress recorded in the checkpoint file. After the local file is uploaded to OSS, the checkpoint file is deleted.
// By default, if you do not specify this parameter, the checkpoint file is stored in the same directory as the local file that you want to upload. The directory is named ${uploadFile}.ucp.
uploadFileRequest.setCheckpointFile("yourCheckpointFile");
// Configure object metadata.
uploadFileRequest.setObjectMetadata(meta);
// Configure an upload callback. The parameter type is Callback.
//uploadFileRequest.setCallback("yourCallbackEvent");
// Start resumable upload.
ossClient.uploadFile(uploadFileRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
// Shut down the OSSClient instance.
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
const OSS = require('ali-oss')
const client = new OSS({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
});
// Set yourfilepath to the local path of the file to upload.
const filePath = "yourfilepath";
let checkpoint;
async function resumeUpload() {
// Retry five times.
for (let i = 0; i < 5; i++) {
try {
const result = await client.multipartUpload('object-name', filePath, {
checkpoint,
async progress(percentage, cpt) {
checkpoint = cpt;
},
});
console.log(result);
break; // Break the current loop.
} catch (e) {
console.log(e);
}
}
}
resumeUpload();using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt.
// By default, if you specify only the name of the local file such as examplefile.txt without specifying the local path, the local file is uploaded from the path of the project to which the sample program belongs.
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the checkpoint file. The checkpoint file stores information about the upload progress.
string checkpointDir = "yourCheckpointDir";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Configure parameters by using UploadFileRequest.
UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename)
{
// Specify the size of each part.
PartSize = 8 * 1024 * 1024,
// Specify the number of concurrent threads.
ParallelThreadCount = 3,
// Specify the checkpointDir parameter to store the state of the resumable upload task, which is used to resume the upload task if the upload task fails.
// If you set checkpointDir to null, resumable upload does not take effect and the object is re-uploaded if the object fails to be uploaded.
CheckpointDir = checkpointDir,
};
// Start resumable upload.
client.ResumableUploadObject(request);
Console.WriteLine("Resumable upload object:{0} succeeded", objectName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}// Obtain the UploadId to upload the file.
OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
resumableUpload.bucketName = <bucketName>;
// objectKey is the same as objectName. It specifies the full path of the object that you want to upload to OSS, including the file extension. For example, abc/efg/123.jpg.
resumableUpload.objectKey = <objectKey>;
resumableUpload.partSize = 1024 * 1024;
resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// Set the path to save the breakpoint record.
resumableUpload.recordDirectoryPath = cachesDir;
// Set the deleteUploadIdOnCancelling parameter to NO. This indicates that the breakpoint record file is not deleted. If the upload fails, the upload resumes from the breakpoint until the file is completely uploaded. If you do not set this parameter, the default value YES is used. This indicates that the breakpoint record file is deleted. The next time you upload the same file, the upload starts from the beginning.
resumableUpload.deleteUploadIdOnCancelling = NO;
resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:<your file path>];
OSSTask * resumeTask = [client resumableUpload:resumableUpload];
[resumeTask continueWithBlock:^id(OSSTask *task) {
if (task.error) {
NSLog(@"error: %@", task.error);
if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
// This task cannot be resumed. You must obtain a new uploadId to re-upload the file.
}
} else {
NSLog(@"Upload file success");
}
return nil;
}];
// [resumeTask waitUntilFinished];
// [resumableUpload cancel];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, for example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project where the sample program is located. */
std::string UploadFilePath = "D:\\localpath\\examplefile.txt";
/* The file that records the results of local part uploads. The upload progress is saved in this file. If a part fails to upload, the next upload attempt resumes from the breakpoint recorded in the file. After the upload is complete, this file is deleted. */
/* Set the directory where the checkpoint file is stored and make sure the specified directory exists, for example, D:\\local. If this value is not set, checkpoint information is not recorded and resumable upload is not used. */
std::string CheckpointFilePath = "D:\\local";
/* Initialize network and other resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Perform a resumable upload. */
UploadObjectRequest request(BucketName, ObjectName, UploadFilePath, CheckpointFilePath);
auto outcome = client.ResumableUploadObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ResumableUploadObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network and other resources. */
ShutdownSdk();
return 0;
}#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the bucket's region. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name, such as examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "yourLocalFilename";
/* Set yourRegion to the Region of the bucket. For example, for the China (Hangzhou) region, set the Region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// You must also configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specifies whether a CNAME is used. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* At the program entry point, call the aos_http_io_initialize method to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* A memory pool for memory management. It is equivalent to apr_pool_t. The implementation is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configurations such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_list_t resp_body;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
oss_resumable_clt_params_t *clt_params;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
aos_str_set(&file, local_filename);
aos_list_init(&resp_body);
/* Perform a resumable upload. */
clt_params = oss_create_resumable_clt_params_content(pool, 1024 * 100, 3, AOS_TRUE, NULL);
resp_status = oss_resumable_upload_file(oss_client_options, &bucket, &object, &file, headers, NULL, clt_params, NULL, &resp_headers, &resp_body);
if (aos_status_is_ok(resp_status)) {
printf("resumable upload succeeded\n");
} else {
printf("resumable upload failed\n");
}
/* Release the memory pool. This releases the memory allocated for resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the script's purpose: upload file sample
parser = argparse.ArgumentParser(description="upload file sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket to which the file is uploaded. This is a required parameter.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the key of the object (file) in OSS. This is a required parameter.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --file_path command-line argument, which specifies the path of the local file to be uploaded. This is a required parameter, for example, "/Users/yourLocalPath/yourFileName".
parser.add_argument('--file_path', help='The path of Upload file.', required=True)
def main():
# Parse the command-line arguments to obtain the user-provided values.
args = parser.parse_args()
# Load the authentication information required to access OSS from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Create a configuration object using the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region property of the configuration object based on the command-line arguments provided by the user.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
client = oss.Client(cfg)
# Create an object for uploading files, enable resumable upload, and specify the path to save the breakpoint record file.
uploader = client.uploader(enable_checkpoint=True, checkpoint_dir="/Users/yourLocalPath/checkpoint/")
# Call the method to perform the file upload operation.
result = uploader.upload_file(
oss.PutObjectRequest(
bucket=args.bucket, # Specify the destination bucket.
key=args.key, # Specify the name of the file in OSS.
),
filepath=args.file_path # Specify the location of the local file.
)
# Print information about the upload result, including the status code, request ID, and Content-MD5.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.headers.get("Content-MD5")},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
f' server time: {result.headers.get("x-oss-server-time")},'
)
# When this script is executed directly, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script. The program flow starts from here.<?php
// Import autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region where the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) The name of the object.
];
// Construct an array of long options required by getopt.
// Add a colon (:) to the end of each key to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Check whether all required arguments are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the argument help information.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the path of the local file to be uploaded.
$filename = "/Users/yourLocalPath/yourFileName"; // The sample file path.
// Create an Uploader instance.
$uploader = $client->newUploader();
// Perform the multipart upload operation.
$result = $uploader->uploadFile(
request: new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key), // Create a PutObjectRequest object to specify the names of the bucket and object.
filepath: $filename, // Specify the path of the local file to be uploaded.
);
// Display the result of the multipart upload.
printf(
'multipart upload status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. The status code 200 indicates that the request was successful.
'multipart upload request id:' . $result->requestId . PHP_EOL . // The request ID used for debugging or tracking the request.
'multipart upload result:' . var_export($result, true) . PHP_EOL // The detailed results of the multipart upload.
);
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The storage region.
bucketName string // The bucket name.
objectName string // The object name.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the source object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source object name required")
}
// Load the default configurations and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create an uploader.
u := client.NewUploader()
// Define the local file path. You need to replace the path with the actual local file path and filename.
localFile := "/Users/yourLocalPath/yourFileName"
// Upload the file.
result, err := u.UploadFile(context.TODO(),
&oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName)},
localFile)
if err != nil {
log.Fatalf("failed to upload file %v", err)
}
// Print the upload result.
log.Printf("upload file result:%#v\n", result)
}