Este tópico apresenta um exemplo de código para upload multipart de fluxos de dados com o Object Storage Service (OSS) SDK for Java.
Observações
Este exemplo usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.
As credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Uma instância OSSClient é criada com um endpoint público do OSS. Para criar uma instância OSSClient com um nome de domínio personalizado ou Security Token Service (STS), consulte Configurar um cliente.
Para concluir todo o processo de upload multipart, incluindo InitiateMultipartUpload, UploadPart e CompleteMultipartUpload, você precisa da permissão
oss:PutObject. Para obter mais informações sobre como conceder essa permissão, consulte Exemplos comuns de políticas do RAM.
Código de exemplo
O código a seguir realiza o upload multipart de fluxos de dados:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.*;
public class MultipartUploadforStream {
public static void main(String[] args) throws Exception {
// In this example, the endpoint for the China (Hangzhou) region is used.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
String objectName = "exampledir/exampleobject.txt";
// Specify the path of the local file that you want to upload.
String filePath = "/Users/localFilePath/example.txt";
// Specify the region where 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";
// Create an OSSClient instance.
// When the OSSClient instance is no longer USED, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an InitiateMultipartUploadRequest object.
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
ObjectMetadata metadata = new ObjectMetadata();
if (metadata.getContentType() == null) {
metadata.setContentType(Mimetypes.getInstance().getMimetype(new File(filePath), objectName));
}
System.out.println("Content-Type: " + metadata.getContentType());
request.setObjectMetadata(metadata);
// Initiate the multipart upload task and obtain the upload ID in the response.
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
String uploadId = upresult.getUploadId();
// partETags is a list of PartETags.
List<PartETag> partETags = new ArrayList<>();
// Calculate the number of parts.
File sampleFile = new File(filePath);
long fileLength = sampleFile.length();
final long partSize = 5 * 1024 * 1024L; // Set the part size to 5 MB.
// Upload all parts.
try (FileInputStream instream = new FileInputStream(sampleFile)) {
byte[] buffer = new byte[8192]; // Set the buffer.
long remaining = fileLength;
int partNumber = 1;
while (remaining > 0) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
long bytesToRead = Math.min(partSize, remaining);
int bytesRead;
long totalRead = 0;
while (totalRead < bytesToRead && (bytesRead = instream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
totalRead += bytesRead;
}
// Construct the part stream.
InputStream partStream = new ByteArrayInputStream(baos.toByteArray());
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(partStream);
uploadPartRequest.setPartSize(totalRead);
uploadPartRequest.setPartNumber(partNumber++);
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
partETags.add(uploadPartResult.getPartETag());
remaining -= totalRead;
}
}
// Create a CompleteMultipartUploadRequest object.
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// Complete the multipart upload task.
CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
System.out.println("Upload successful, ETag: " + completeMultipartUploadResult.getETag());
} 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 a 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.
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Referências
Para obter mais informações sobre upload multipart no OSS, consulte Upload multipart (Java SDK V1).