Commit 73664db4 by yixinjj

添加注释

1 parent 098d35a5
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head>
<meta charset="utf-8" /> <head>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8" />
<title>file upload oss</title> <meta name="viewport" content="width=device-width, initial-scale=1">
</head> <title>file upload oss</title>
<body> </head>
<script src="js/uni.webview.1.5.5.js"></script>
<script src="js/aliyun-oss-sdk-6.18.1.min.js"></script> <body>
<script src="js/OSSUpLoader.js"></script> <script src="js/uni.webview.1.5.5.js"></script>
<script> <script src="js/aliyun-oss-sdk-6.18.1.min.js"></script>
// document.addEventListener('UniAppJSBridgeReady', function(){ <script src="js/OSSUpLoader.js"></script>
window.msgFromUniapp = function(accessKeyId, accessKeySecret, stsToken, fileName, options = {}) { <script>
if (!accessKeyId || !accessKeySecret || !stsToken || !fileName) { // document.addEventListener('UniAppJSBridgeReady', function(){
throw new Error('accessKeyId,accessKeySecret,stsToken,fileName is required') /**
} * 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
const opt = Object.assign({ accessKeyId,accessKeySecret,stsToken }, options) * @param {string} accessKeyId - OSS 访问密钥 ID
let uploader = new OSSUpLoader(opt) * @param {string} accessKeySecret - OSS 访问密钥 secret
uploader.upload(fileName, function(result) { * @param {string} stsToken - 安全令牌服务(STS)令牌,用于临时访问 OSS 存储桶
* @param {string} fileName - 要上传的文件名
* @param {Object} options - (可选)包含上传器配置的对象,如 region
* @throws {Error} 如果缺少必要的参数,将抛出错误
*/
window.msgFromUniapp = function (accessKeyId, accessKeySecret, stsToken, fileName, options = {}) {
if (!accessKeyId || !accessKeySecret || !stsToken || !fileName) {
throw new Error('accessKeyId,accessKeySecret,stsToken,fileName is required')
}
try {
// 使用 Object.assign 合并默认配置参数和传入的 options 参数
const opt = Object.assign({ accessKeyId, accessKeySecret, stsToken }, options);
// 创建 OSSUpLoader 实例,传入配置对象
let uploader = new OSSUpLoader(opt);
// 调用 upload 方法上传文件,并在完成后处理结果
uploader.upload(fileName, function (result) {
// 通过 uni.postMessage 将上传结果作为数据发送
uni.postMessage({ uni.postMessage({
data: { data: {
...result, ...result,
fileName fileName
} }
}); });
uploader.destroy() // 调用 destroy 方法,这将重置上传器的状态,释放资源
uploader = null uploader.destroy();
}) // 将 uploader 置为 null,释放内存
uploader = null;
});
} catch (e) {
// 如果发生错误,将错误信息作为数据发送
uni.postMessage({
data: {
code: 1,
fileName,
error: e.message
}
});
} }
// }, false); // }, false);
</script> </script>
</body> </body>
</html> </html>
\ No newline at end of file \ No newline at end of file
class OSSUpLoader { class OSSUpLoader {
/** /**
* yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。 * yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
*/ */
region = "oss-cn-shenzhen"; region = "oss-cn-shenzhen";
/** /**
* 填写Bucket名称。 * 填写Bucket名称。
*/ */
bucket = 'glsk-oss'; bucket = "glsk-oss";
/** /**
* 文件类型 * 文件的 MIME 类型
*/ */
mime = "audio/mpeg"; mime = "audio/mpeg";
/** /**
* 本地保存文件路径(待上传文件路径) * 本地保存文件路径(待上传文件路径)
*/ */
filePath = 'file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/' filePath =
/** "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/";
* 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。 /**
*/ * 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
accessKeyId; */
/** accessKeyId;
* 从STS服务获取的安全令牌(SecurityToken)。 /**
*/ * 从STS服务获取的安全令牌(SecurityToken)。
accessKeySecret; */
/** accessKeySecret;
* 从STS服务获取的安Token。 /**
*/ * 从STS服务获取的安Token。
stsToken; */
/** stsToken;
* OSS 文件上传实例 /**
*/ * OSS 文件上传实例
client = null; */
/** client = null;
* 上传并发数 /**
*/ * 同时上传的最大任务数
parallel = 4; */
/** parallel = 4;
* 设置分片大小。500kb。 /**
*/ * 每个上传分片的大小(字节)。默认500kb。
partSize = 500; */
/** partSize = 500;
* 最小文件大小 /**
*/ * 最小文件大小
minPartSize = 100; */
/** minPartSize = 100;
* 超时时间:默认60s /**
*/ * 上传任务的超时时间(毫秒):默认60
timeout = 60 * 1000; */
// headers, timeout = 60 * 1000;
/** // headers,
* 自定义元数据,通过HeadObject接口可以获取Object的元数据。 /**
*/ * 自定义元数据,通过HeadObject接口可以获取Object的元数据。
meta = {}; */
/** meta = {};
* 初始化重传次数 /**
*/ * 初始化重传次数
retryCount = 0; */
/** retryCount = 0;
* 失败重传次数 /**
*/ * 上传失败时的最大重试次数
retryCountMax = 3; */
/** retryCountMax = 3;
* 失败重传间隔 /**
*/ * 上传失败时的重试间隔时间(毫秒)
retryInterval = 3 * 1000 */
currentCheckpoint; retryInterval = 3 * 1000;
/** currentCheckpoint;
* OSS文件夹 /**
*/ * OSS 存储桶中的目标文件夹路径
ossFolder='quality/'; */
/** ossFolder = "quality/";
* 构造函数 /**
*/ * 构造函数
constructor({ */
region = this.region, constructor({
bucket = this.bucket, region = this.region,
accessKeyId, bucket = this.bucket,
accessKeySecret, accessKeyId,
stsToken, accessKeySecret,
mime = this.mime, stsToken,
partSize = this.partSize, mime = this.mime,
parallel = this.parallel, partSize = this.partSize,
timeout = this.timeout, parallel = this.parallel,
filePath = this.filePath, timeout = this.timeout,
retryCountMax = this.retryCountMax, filePath = this.filePath,
retryInterval = this.retryInterval, retryCountMax = this.retryCountMax,
ossFolder = this.ossFolder retryInterval = this.retryInterval,
}) { ossFolder = this.ossFolder,
if (partSize && partSize < this.minPartSize) { }) {
throw new Error(common.constants.CODE.FILE_PART_SIZE_TOO_SMALL) if (partSize < this.minPartSize) {
} throw new Error(common.constants.CODE.FILE_PART_SIZE_TOO_SMALL);
this.mime = mime }
this.partSize = partSize this.mime = mime;
this.parallel = parallel this.partSize = partSize;
this.filePath = filePath this.parallel = parallel;
this.retryCountMax = retryCountMax this.timeout = timeout;
this.retryInterval = retryInterval this.filePath = filePath;
this.ossFolder = ossFolder this.retryCountMax = retryCountMax;
//实例化OSS this.retryInterval = retryInterval;
this.client = new OSS({ this.ossFolder = ossFolder;
region, //实例化OSS
bucket, this.client = new OSS({
accessKeyId, region,
accessKeySecret, bucket,
stsToken, accessKeyId,
}); accessKeySecret,
} stsToken,
/**文件上传函数(外部调用) });
* @param {Object} fileName 文件名 }
* @param {Object} callback 回调函数 /**
*/ * 上传文件到指定的 OSS 存储空间
upload(fileName, callback) { * @param {string} fileName - 要上传的文件名
this._pathToFile(this.filePath + fileName, function(result) { * @param {Function} callback - 文件上传完成或失败后的回调函数
if (result.code === common.constants.CODE.FILE_PATH_TRANSFORM_SUCCESS) { * @throws {Error} 如果文件路径转换失败,将抛出错误
this._upload(fileName, result.data.file, callback) */
} else { upload(fileName, callback) {
callback(result) this._pathToFile(
} this.filePath + fileName,
}.bind(this)) function (result) {
} if (result.code === common.constants.CODE.FILE_PATH_TRANSFORM_SUCCESS) {
/**文件上传(内部方法) this._upload(fileName, result.data.file, callback);
* @param {Object} fileName 文件名 } else {
* @param {Object} file 文件 callback(result);
* @param {Object} callback 回调函数 }
*/ }.bind(this)
_upload(fileName, file, callback) { );
this.client.multipartUpload(this.ossFolder+fileName, file, { }
// 获取分片上传进度、断点和返回值。
progress: (p, checkpoint, res) => {
this.currentCheckpoint = checkpoint;
console.log(p);
},
// 设置并发上传的分片数量。
parallel: this.parallel,
//分片大小(kb) 最小为100kb 默认500kb
partSize: 1024 * this.partSize,
timeout: this.timeout,
mime: this.mime,
}).then((res) => {
// console.log(JSON.stringify(res),res.status,res.status==200)
if (res.res.statusCode == 200) {
// console.log('upload success: %j', JSON.stringify(res));
this.currentCheckpoint = null;
this.retryCount = 0
callback(common.genCallBacks('FILE_UPLOAD_OSS_SUCCESS', {
errFromOSS: res
}))
} else {
callback(common.genCallBacks('FILE_UPLOAD_OSS_FAIL', {
errMsg: `OSS返回错误 状态码: ${res.status}`,
errFromOSS: res
}))
}
}).catch(err => { /**
console.error(err); * 将文件上传到对象存储服务(OSS)
console.log(`err.name : ${err.name}`); *
console.log(`err.message : ${err.message}`); * @param {string} fileName - 要上传的文件名(包括扩展名)
// if (err.name.toLowerCase().indexOf('connectiontimeout') !== -1) { * @param {File} file - 要上传的文件对象
// timeout retry * @param {Function} callback - 上传完成或发生错误时调用的回调函数
if (this.retryCount < this.retryCountMax) { *
this.retryCount++; * @throws {Error} 如果文件路径转换失败,将抛出错误
console.error(`retryCount : ${this.retryCount}`); */
setTimeout(() => { _upload(fileName, file, callback) {
this._upload(fileName, file, callback); this.client
}, this.retryInterval) .multipartUpload(this.ossFolder + fileName, file, {
} else { // 获取分片上传进度、断点和返回值。
callback(common.genCallBacks('FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER', { progress: (p, checkpoint, res) => {
errMsg: err.message, this.currentCheckpoint = checkpoint;
err console.log(p);
})) },
} // 设置并发上传的分片数量。
// } parallel: this.parallel,
}) //分片大小(kb) 最小为100kb 默认500kb
} partSize: 1024 * this.partSize,
timeout: this.timeout,
mime: this.mime,
})
.then((res) => {
// console.log(JSON.stringify(res),res.status,res.status==200)
if (res.res.statusCode == 200) {
// console.log('upload success: %j', JSON.stringify(res));
this.currentCheckpoint = null;
this.retryCount = 0;
callback(
common.genCallBacks("FILE_UPLOAD_OSS_SUCCESS", {
errFromOSS: res,
})
);
} else {
callback(
common.genCallBacks("FILE_UPLOAD_OSS_FAIL", {
errMsg: `OSS返回错误 状态码: ${res.status}`,
errFromOSS: res,
})
);
}
})
.catch((err) => {
console.error(err);
console.log(`err.name : ${err.name}`);
console.log(`err.message : ${err.message}`);
// if (err.name.toLowerCase().indexOf('connectiontimeout') !== -1) {
// timeout retry
if (this.retryCount < this.retryCountMax) {
this.retryCount++;
console.error(`retryCount : ${this.retryCount}`);
setTimeout(() => {
this._upload(fileName, file, callback);
}, this.retryInterval);
} else {
callback(
common.genCallBacks("FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER", {
errMsg: err.message,
err,
})
);
}
// }
});
}
/**将文件路径转成文件对象 /**
* @param {Object} filePath 文件路径 * 将文件路径转换为可下载的文件对象
* @param {Object} callback 回调函数 *
*/ * @param {string} filePath - 文件的路径
_pathToFile(filePath, callback) { * @param {Function} callback - 转换完成时调用的回调函数
window.webkitURL = window.webkitURL || window.URL; *
var xhr = new XMLHttpRequest(); * @throws {Error} 如果请求过程中发生错误,将抛出错误
xhr.open("GET", filePath, true); */
xhr.responseType = "blob"; _pathToFile(filePath, callback) {
xhr.onload = function() { window.webkitURL = window.webkitURL || window.URL;
if (this.status == 200) { var xhr = new XMLHttpRequest();
var file = this.response xhr.open("GET", filePath, true);
callback(common.genCallBacks('FILE_PATH_TRANSFORM_SUCCESS', { xhr.responseType = "blob";
file xhr.onload = function () {
})) if (this.status == 200) {
} else { var file = this.response;
callback(common.genCallBacks('FILE_PATH_TRANSFORM_FAIL')) callback(
} common.genCallBacks("FILE_PATH_TRANSFORM_SUCCESS", {
}; file,
xhr.onerror = function(errType, errMsg) { })
callback(common.genCallBacks('FILE_PATH_REQUEST_FAIL', { );
errType, } else {
errMsg callback(common.genCallBacks("FILE_PATH_TRANSFORM_FAIL"));
})) }
}; };
xhr.send(); xhr.onerror = function (errType, errMsg) {
} callback(
destroy(){ common.genCallBacks("FILE_PATH_REQUEST_FAIL", {
this.retryCount = 0 errType,
this.client = null errMsg,
} })
}; );
};
xhr.send();
}
/**
* 销毁当前实例对象,释放资源并重置状态
* 该方法将重置上传器的重试次数为 0,并将客户端实例置为 null
*/
destroy() {
this.retryCount = 0;
this.client = null;
}
}
const common = { const common = {
constants: {
CODE: {
FILE_PATH_TRANSFORM_SUCCESS: 0,
FILE_PATH_REQUEST_FAIL: 1,
FILE_PATH_TRANSFORM_FAIL: 2,
FILE_UPLOAD_OSS_SUCCESS: 0,
FILE_UPLOAD_OSS_FAIL: 3,
FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER: 4
},
MESSAGE: {
FILE_PATH_TRANSFORM_SUCCESS: '文件转换成功',
FILE_PATH_REQUEST_FAIL: '文件转换请求失败',
FILE_PATH_TRANSFORM_FAIL: '文件转换失败',
FILE_UPLOAD_OSS_SUCCESS: '文件上传至OSS成功',
FILE_UPLOAD_OSS_FAIL: '文件上传至OSS失败',
FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER: '文件上传至OSS超时或其他错误',
FILE_PART_SIZE_TOO_SMALL:'分片大小不能小于100kb'
}
},
genCallBacks(key, data = {}) {
const {
CODE,
MESSAGE
} = common.constants
return {
code: CODE[key],
message: MESSAGE[key],
data
}
}
}
\ No newline at end of file \ No newline at end of file
constants: {
CODE: {
FILE_PATH_TRANSFORM_SUCCESS: 0,
FILE_PATH_REQUEST_FAIL: 1,
FILE_PATH_TRANSFORM_FAIL: 2,
FILE_UPLOAD_OSS_SUCCESS: 0,
FILE_UPLOAD_OSS_FAIL: 3,
FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER: 4,
},
MESSAGE: {
FILE_PATH_TRANSFORM_SUCCESS: "文件转换成功",
FILE_PATH_REQUEST_FAIL: "文件转换请求失败",
FILE_PATH_TRANSFORM_FAIL: "文件转换失败",
FILE_UPLOAD_OSS_SUCCESS: "文件上传至OSS成功",
FILE_UPLOAD_OSS_FAIL: "文件上传至OSS失败",
FILE_UPLOAD_OSS_TIMEOUT_OR_OTHER: "文件上传至OSS超时或其他错误",
FILE_PART_SIZE_TOO_SMALL: "分片大小不能小于100kb",
},
},
/**
* 生成回调对象
*
* @param {string} key -回调键值
* @param {Object} data - 回调数据对象
* @return {Object} 回调对象
*/
genCallBacks(key, data = {}) {
const { CODE, MESSAGE } = common.constants;
return {
code: CODE[key],
message: MESSAGE[key],
data,
};
},
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!