This topic describes how to download an object to a local computer.
Usage notes
Before you run the sample code in this topic, you must create an OSSClient instance by using methods such as using a custom domain name or Security Token Service (STS). For more information, see Initialization.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM Policy or Bucket policies.
API | Action | Definition |
GetObject |
| Downloads an object. |
| When downloading an object, if you specify the object version through versionId, this permission is required. | |
| When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required. |
Example
The following code provides an example on how to download a specific object to a local computer:
// Construct an object download request.
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path.
GetObjectRequest get = new GetObjectRequest("examplebucket", "exampledir/exampleobject.txt");
oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// Start reading data.
long length = result.getContentLength();
if (length > 0) {
byte[] buffer = new byte[(int) length];
int readCount = 0;
while (readCount < length) {
try{
readCount += result.getObjectContent().read(buffer, readCount, (int) length - readCount);
}catch (Exception e){
OSSLog.logInfo(e.toString());
}
}
// Specify the full path of the downloaded object. Example: D:\\localpath\\exampleobject.jpg.
try {
FileOutputStream fout = new FileOutputStream("download_filePath");
fout.write(buffer);
fout.close();
} catch (Exception e) {
OSSLog.logInfo(e.toString());
}
}
}
@Override
public void onFailure(GetObjectRequest request, ClientException clientException,
ServiceException serviceException) {
}
});References
For the complete sample code that is used to download an object to a local computer, visit GitHub.
For more information about the API operation that you can call to download an object to a local computer, see GetObject.
For more information about how to initialize an OSSClient instance, see Initialization.