Si solo necesita una parte de los datos de un archivo, utilice la descarga por rango para recuperar los datos dentro de un intervalo específico.
Notas de uso
Cuando use herramientas de empaquetado como Webpack y Browserify, instale OSS SDK for Browser.js mediante el comando npm install ali-oss.
Si desea acceder a un bucket de OSS desde un navegador, pero no hay reglas de CORS configuradas para ese bucket, el navegador rechazará la solicitud. Por lo tanto, debe configurar las reglas de CORS en el bucket para poder acceder a él desde un navegador. Para obtener más información, consulte Installation.
-
En la mayoría de los casos, OSS SDK for Browser.js se utiliza en navegadores. Para evitar que su par de AccessKey quede expuesto, se recomienda usar credenciales de acceso temporales obtenidas de Security Token Service (STS) para acceder a OSS.
Las credenciales de acceso temporales constan de un par de AccessKey y un token de seguridad. El par de AccessKey incluye un AccessKey ID y un AccessKey secret. Para obtener más información sobre cómo conseguir credenciales de acceso temporales, consulte Use STS for temporary access authorization.
Código de ejemplo
A continuación se muestra un código de ejemplo que indica cómo ejecutar una descarga por rango:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='download'>Download</button>
<!--Import the SDK file.-->
<script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
<script type="text/javascript">
const client = new OSS({
// Set region to the region where your bucket is located. For example, if your bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
// Get the DOM element.
const download = document.getElementById('download')
// For a 1000-byte file, the valid byte range is 0 to 999.
// If the specified range is invalid, for example, the start or end position is a negative value or is greater than the file size, the entire file is downloaded.
const start = 0, end = 999
// Add a listener to the button.
download.addEventListener('click', () => {
client.get('example.txt',{
headers: {
Range: `bytes=${start}-${end}`,
},
}).then(r => {
// Convert the returned data into a downloadable object in BLOB format.
const newBlob = new Blob([r.content], { type: r.res.headers['content-type'] });
// Create an anchor element.
const link = document.createElement('a')
// Attach the href property to the element.
link.href = window.URL.createObjectURL(newBlob)
// Specify the name of the local file.
link.download = 'example.txt'
// Download the object.
link.click()
// Remove the attached URL.
window.URL.revokeObjectURL(link.href)
})
})
</script>
</body>
</html>
Referencias
Para consultar el código de ejemplo completo de las descargas por rango, revise el ejemplo de GitHub.
Para conocer la referencia de la API de descargas por rango, consulte GetObject.