详情介绍

1. 服务器端参数详解:
- `Range`:指定请求的起始和结束位置,例如`GET /file?start=0&end=50`表示请求从第0个字节开始,到第50个字节结束。
- `Accept-Ranges`:设置响应的Content-Range头部,告诉客户端从哪个位置开始接收数据。
- `Cache-Control`:设置缓存策略,如`max-age=3600`表示缓存有效期为1小时。
- `Expires`:设置响应的过期时间,如`Expires: Sun, 26 Jul 2017 08:49:07 GMT`表示响应在2017年7月26日08:49:07之前有效。
- `Content-Length`:返回响应的字节长度,如`Content-Length: 1024`表示响应包含1024字节。
- `Content-Type`:返回响应的内容类型,如`Content-Type: text/; charset=UTF-8`表示响应是HTML文本,字符集为UTF-8。
- `Last-Modified`:返回响应的最后修改时间,如`Last-Modified: Wed, 21 Oct 2017 17:45:37 GMT`表示响应在2017年10月21日17:45:37之前有效。
- `ETag`:返回响应的实体唯一标识符,如`ETag: "abcdefg"`表示响应的实体唯一标识符为"abcdefg"。
- `Server`:设置服务器信息,如`Server: Apache/2.4.7 (Ubuntu)`表示服务器为Apache/2.4.7版本。
2. 配置教程:
以Node.js为例,使用axios库进行断点续传配置:
javascript
const axios = require('axios');
const fs = require('fs');
const path = require('path');
// 获取文件路径
const filePath = path.join(__dirname, 'example.txt');
// 读取文件内容
async function readFile(filePath) {
const data = await fs.promises.readFile(filePath);
return data;
}
// 发送请求
async function downloadFile(url, start, end) {
const response = await axios({
method: 'HEAD',
url: url,
responseType: 'arraybuffer',
});
if (response.headers['content-range'] && response.headers['content-range'].includes('bytes=')) {
const range = response.headers['content-range'];
const parts = range.split('bytes=');
const start = parseInt(parts[0]);
const end = parseInt(parts[1]);
const contentLength = response.headers['content-length'];
if (contentLength > 0) {
const chunkSize = contentLength / (end - start + 1);
const buffer = new ArrayBuffer(chunkSize);
const view = new DataView(buffer);
for (let i = start; i < end; i++) {
view.setUint8(i, response.headers['content-type'].indexOf('binary') === -1 ? 0 : response.headers['content-type'].indexOf('binary', i) + 1);
}
return buffer;
} else {
throw new Error('Invalid Range');
}
} else {
throw new Error('Invalid Range');
}
}
// 下载文件并处理断点续传
async function downloadFileWithRange(url, start, end) {
const response = await axios({
method: 'GET',
url: url,
responseType: 'arraybuffer',
});
if (response.status === 206 || response.status === 206 && response.headers['content-range']) {
const contentLength = response.headers['content-length'];
const range = response.headers['content-range'];
const start = Number(range.match(/bytes=(\d+)/)[1]);
const end = Number(range.match(/bytes=(\d+)/)[2]);
const contentLengthInBytes = contentLength / (end - start + 1);
const buffer = await downloadFile(url, start, end);
const downloadedFile = fs.createWriteStream(filePath);
downloadedFile.on('finish', () => {
downloadedFile.close();
console.log('Downloaded file successfully');
});
downloadedFile.on('error', (err) => {
console.error('Error downloading file:', err);
});
downloadedFile.write(buffer);
downloadedFile.end();
} else {
console.error('Invalid Range');
}
}
// 示例用法
downloadFileWithRange('https://example.com/example.txt', 0, 50);
注意:以上代码仅作为示例,实际应用中需要根据具体需求进行调整。