You can call the PutObject operation to upload a single object smaller than 5 GB. This is referred to as simple upload. Simple upload is suitable for scenarios in which an object can be uploaded by sending a single HTTP request.
Prerequisites
Precautions
- Object size
The size of the object that you can upload by means of simple upload cannot exceed 5 GB. To upload an object larger than 5 GB, use multipart upload. For more information, see Multipart upload and resumable upload.
- Naming conventions
- The name must be encoded in UTF-8.
- The name must be 1 to 1,023 characters in length.
- The name cannot start with a forward slash (/) or a backslash (\).
- Upload security and authorization
To prevent unauthorized third-party users from uploading data to your bucket, Object Storage Service (OSS) provides bucket-level and object-level access control. For more information, see Overview.
To authorize third-party users to upload objects to your buckets, OSS also provides account-level authorization. For more information, see Authorized third-party upload.
- Prevent existing objects from being overwritten by objects with the same names
By default, when you upload an object to OSS, an existing object with the same name is overwritten by the uploaded object. You can use the following methods to prevent your objects from being unexpectedly removed:
- Enable versioning
If versioning is enabled, overwritten objects are saved as previous versions. You can restore an object to a previous version at any time. For more information, see Overview.
- Include a specific parameter in the upload request
Include the x-oss-forbid-overwrite parameter in the upload request header and set the parameter to true. This way, if you upload an object that has the same name as an existing object, the upload fails and OSS returns the
FileAlreadyExists
error. If this parameter is not included in the request header, or this parameter is set to false, the object that has the same name is overwritten.
- Enable versioning
- Optimize object upload performance
If you upload a large number of objects with sequential prefixes such as timestamps and letters in the object names, many object indexes may be stored in a single partition. In this case, if you send a large number of requests to query these objects, the latency may increase. We recommend that you use random prefixes but not sequential prefixes for object names when you upload a large number of objects. For more information, see OSS performance and scalability best practices.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket to which you want to upload objects.
- In the left-side navigation pane, click the Files tab. On the page that appears, click Upload.
- In the Upload panel, configure the parameters described in the following table.
Use ossbrowser
Operations related to buckets supported by ossbrowser are similar to those supported by the OSS console. You can follow the guidelines listed on the ossbrowser interface to complete simple upload operations. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
The following code provides an example on how to perform simple upload by using OSS SDKs for common programming languages. For more information about how to perform simple upload by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.ByteArrayInputStream;
public class Demo {
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";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Specify the string that you want to upload.
String content = "Hello OSS";
// Create a PutObjectRequest object.
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// Optional. Specify the storage class and the access control list (ACL) of the object.
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// Upload the string.
ossClient.putObject(putObjectRequest);
} 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 (ClientException 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 {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the name of the bucket to which you want to upload the object. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";
// <yourLocalFile> consists of a local file path and a file name with an extension. Example: /users/local/myfile.txt.
// Specify the full path of the local file to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the local file, the local file is uploaded from the path of the project to which the sample program belongs.
$filePath = "D:\\localpath\\examplefile.txt";
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->uploadFile($bucket, $object, $filePath);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
# -*- coding: utf-8 -*-
import oss2
import os
# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS, because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# The file must be opened in binary mode.
# Specify the full path of the local file. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs.
with open('D:\\localpath\\examplefile.txt', 'rb') as fileobj:
# Use the seek method to read data from byte 1000 of the file. The data is uploaded from byte 1000 to the last byte of the local file.
fileobj.seek(1000, os.SEEK_SET)
# Use the tell method to obtain the current position.
current = fileobj.tell()
# Specify the full path of the object. The full path of the object cannot contain the bucket name.
bucket.put_object('exampleobject.txt', fileobj)
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your business requirements.
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
err = bucket.PutObjectFromFile("exampledir/exampleobject.txt", "D:\\localpath\\examplefile.txt")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
using Aliyun.OSS;
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
var objectName = "exampleobject.txt";
// Specify the full path of the local file that you want to upload. By default, if you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs.
var localFilename = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Upload the file.
client.PutObject(bucketName, objectName, localFilename);
Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
#include <fstream>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the information about the account that is used to access OSS. */
/* Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS, because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* Specify the full path of the local file that you want to upload, for example, D:\\localpath\\examplefile.txt. In D:\\localpath\\examplefile.txt, localpath indicates the local path in which the file is stored. */
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("D:\\localpath\\examplefile.txt", std::ios::in | std::ios::binary);
PutObjectRequest request(BucketName, ObjectName, content);
/* (Optional) Set the ACL to private and the storage class to Standard for the object that you want to upload by referring to the following sample code. */
//request.MetaData().addHeader("x-oss-object-acl", "private");
//request.MetaData().addHeader("x-oss-storage-class", "Standard");
auto outcome = client.PutObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to perform simple upload by using ossutil, see Simple upload.
Use the RESTful API
If your program requires more custom options to configure pay-by-requester, you can call RESTful API operations. In this case, you must write code to calculate the signature. For more information, see PutObject.
References
- When you use simple upload, you can configure object metadata to describe an object. For example, you can set standard HTTP headers such as Content-Type. You can also configure user metadata. For more information about object metadata, see Manage object metadata.
- After an object is uploaded to OSS, you can use upload callback to send a callback request to a specified application server. For more information, see Upload callback.
- After an image object is uploaded, you can also compress the image object and configure custom styles for the image object. For more information, see IMG implementation modes.