Este tópico descreve o método de upload simples, uma forma direta e rápida de enviar um único arquivo para o OSS.
Precauções
Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
PutObject |
|
Envia um objeto. |
|
|
Necessário se você especificar tags de objeto com o cabeçalho |
|
|
|
Obrigatório quando o cabeçalho |
|
|
|
Código de exemplo
Use o código a seguir para enviar uma string como arquivo para o bucket de destino.
Se você enviar um objeto para um bucket que já contém outro com o mesmo nome, o novo objeto substituirá o existente, desde que você tenha as permissões de acesso necessárias.
import Client, { RequestError } from '@aliyun/oss';
// Create an OSS client instance.
const client = new Client({
// Replace with the Access Key ID of the STS temporary access credential.
accessKeyId: 'yourAccessKeyId',
// Replace with the Access Key Secret of the STS temporary access credential.
accessKeySecret: 'yourAccessKeySecret',
// Replace with the security token of the STS temporary access credential.
securityToken: 'yourSecurityToken',
// Specify 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: 'oss-cn-hangzhou',
});
const bucket = 'yourBucketName'; // Replace with the name of the bucket you want to use.
const key = 'yourObjectName'; // Replace with the name of the object (file) you want to upload.
const putObject = async () => {
try {
// Call the putObject method to upload data to the specified bucket and key, passing the data as a parameter.
const res = await client.putObject({
bucket, // The bucket name.
key, // The object (file) name.
data: 'hello world' // The data to upload. In this case, a simple string.
});
// Print the upload result.
console.log(JSON.stringify(res));
} catch (err) {
// Catch exceptions that occur during the request.
if (err instanceof RequestError) {
// If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
console.log('code: ', err.code);
console.log('message: ', err.message);
console.log('requestId: ', err.requestId);
console.log('status: ', err.status);
console.log('ec: ', err.ec);
} else {
// Print other unknown types of errors.
console.log('unknown error: ', err);
}
}
}
// Call the putObject function to perform the upload operation.
putObject();