Commit d9f63898 by 前端

oss上传

1 parent fcbbd572
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>file upload oss</title>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dolorum in saepe
quia, amet quis, at id aperiam nesciunt incidunt, rerum aut modi facilis
culpa expedita repellat cupiditate vero dicta ut.
</head>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>file upload oss</title>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dolorum in saepe quia, amet quis, at id aperiam nesciunt incidunt, rerum aut modi facilis culpa expedita repellat cupiditate vero dicta ut.
</head>
<body>
<script src="js/uni.webview.1.5.5.js"></script>
<script src="js/aliyun-oss-sdk-6.18.1.min.js"></script>
<script src="js/OSSUpLoader.js"></script>
<script>
// document.addEventListener('UniAppJSBridgeReady', function(){
/**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID
* @param {string} accessKeySecret - OSS 访问密钥 secret
* @param {string} stsToken - 安全令牌服务(STS)令牌,用于临时访问 OSS 存储桶
* @param {string} fileName - 要上传的文件名
* @param {string} filePath - 要上传的文件所在路径
* @param {Object} options - (可选)包含上传器配置的对象,如 region
* @throws {Error} 如果缺少必要的参数,将抛出错误
*/
window.msgFromUniapp = function (accessKeyId, accessKeySecret, stsToken, fileName, filePath, recordId, options = {}) {
if (!accessKeyId || !accessKeySecret || !stsToken || !fileName || !filePath) {
throw new Error('accessKeyId,accessKeySecret,stsToken,fileName,filePath 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({
data: {
...result,
fileName,
recordId,
filePath
}
});
// 调用 destroy 方法,这将重置上传器的状态,释放资源
uploader.destroy();
// 将 uploader 置为 null,释放内存
uploader = null;
});
} catch (e) {
// 如果发生错误,将错误信息作为数据发送
uni.postMessage({
data: {
code: 1,
fileName,
recordId,
filePath,
error: e.message
}
});
}
}
// }, false);
</script>
</body>
</html>
\ No newline at end of file
<body>
<script src="js/uni.webview.1.5.5.js"></script>
<script src="js/aliyun-oss-sdk-6.18.1.min.js"></script>
<script src="js/OSSUpLoader.js"></script>
<script>
// document.addEventListener('UniAppJSBridgeReady', function(){
/**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID
* @param {string} accessKeySecret - OSS 访问密钥 secret
* @param {string} stsToken - 安全令牌服务(STS)令牌,用于临时访问 OSS 存储桶
* @param {string} fileName - 要上传的文件名
* @param {string} filePath - 要上传的文件所在路径
* @param {Object} options - (可选)包含上传器配置的对象,如 region
* @throws {Error} 如果缺少必要的参数,将抛出错误
*/
window.msgFromUniapp = function (
accessKeyId,
accessKeySecret,
stsToken,
fileName,
filePath,
recordId,
options = {}
) {
console.log(fileName, filePath);
if (
!accessKeyId ||
!accessKeySecret ||
!stsToken ||
!fileName ||
!filePath
) {
throw new Error(
"accessKeyId,accessKeySecret,stsToken,fileName,filePath is required"
);
}
try {
// 使用 Object.assign 合并默认配置参数和传入的 options 参数
const opt = Object.assign(
{ accessKeyId, accessKeySecret, stsToken, filePath, recordId },
options
);
// 创建 OSSUpLoader 实例,传入配置对象
let uploader = new OSSUpLoader(opt);
// 调用 upload 方法上传文件,并在完成后处理结果
uploader.upload(fileName, function (result) {
// 通过 uni.postMessage 将上传结果作为数据发送
uni.postMessage({
data: {
...result,
fileName,
recordId,
filePath,
},
});
// 调用 destroy 方法,这将重置上传器的状态,释放资源
uploader.destroy();
// 将 uploader 置为 null,释放内存
uploader = null;
});
} catch (e) {
// 如果发生错误,将错误信息作为数据发送
uni.postMessage({
data: {
code: 1,
fileName,
recordId,
filePath,
error: e.message,
},
});
}
};
// }, false);
</script>
</body>
</html>
......@@ -23,6 +23,9 @@ Vue.component("GlsxImage", GlsxImage);
Vue.component("MessageBox", MessageBox);
Vue.component("wnCanvas", wnCanvas);
Vue.component("UpdateBox", UpdateBox);
import RecordManager from "@/utils/RecordManager";
const recordManager = RecordManager.getInstance();
recordManager.compatible();
uni.$api = api;
uni.$lock = false;
uni.$storage = new Storage();
......
......@@ -86,6 +86,7 @@ export default {
this.setAudioInfo({ endReasonType: 1 });
},
getParams() {
console.log(this.$store.state.user.customerInfo);
const { shopMerchantId, phone, sceneType } = uni.$storage.get("userInfo"),
{ customerName, phoneNumber, salesUuid, carModel, staffName } =
this.$store.state.user.customerInfo,
......@@ -172,6 +173,7 @@ export default {
},
/**保存记录*/
async saveRecord() {
const params = this.getParams();
const unlock = await recordManager.lock();
const recordUrlList = this.audioInfo.audioList.map((i) => {
return {
......@@ -179,8 +181,9 @@ export default {
file: i,
};
});
console.log(this.getParams());
recordManager.addRecord({
...this.getParams(),
...params,
recordUrlList,
});
unlock();
......
......@@ -50,7 +50,12 @@ export default {
filePathOnClient = filePath + fileName,
} = result.detail.data[0];
if (code == 0) {
this.uploadSuccess(recordId, data.filePath, filePathOnClient, fileName);
this.uploadSuccess(
recordId,
data.oss.res.requestUrls[0].split("?")[0],
filePathOnClient,
fileName
);
} else {
this.polling();
}
......@@ -69,8 +74,8 @@ export default {
setTimeout(function () {
var wv = currentWebview.children()[0];
wv.setStyle({ top: "100%", height: 300 });
resolve(wv);
}, 1000); //如果是页面初始化调用时,需要延时一下
resolve(this.wv);
});
},
/**
......@@ -86,7 +91,9 @@ export default {
*/
async enQueue() {
const _snapshot = await this.getRecordsSnapshotFlatten();
console.log(_snapshot, "_snapshot");
this.snapshot = new Queue(_snapshot);
console.log(this.snapshot, "_snapshot");
},
/**
* 获取记录快照并展平数据
......@@ -99,6 +106,7 @@ export default {
*/
async getRecordsSnapshotFlatten() {
const _records = await this.getRecordsSnapshot();
console.log(_records, "_records");
const _snapshot = this.flattenData(_records);
return _snapshot;
},
......@@ -114,8 +122,9 @@ export default {
async uploadRecord(record) {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
wv.evalJS(
`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}')`
console.log(record, "record");
this.wv.evalJS(
`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`
);
},
/**
......@@ -150,9 +159,12 @@ export default {
delete fileInfo.status;
}
});
if (recordFileList.every((i) => i.status === undefined)) {
console.log(recordFileList, "recordFileList");
if (recordFileList.every((i) => i.status == undefined)) {
const res = await uni.$api.commonApi.saveRecCustomer(record);
if (res.code == 0) {
console.log(res);
if (res) {
recordManager.removeRecord(recordId);
}
} else {
......@@ -191,7 +203,7 @@ export default {
cur.recordUrlList.map((file) => {
const aFullPath = file.file.split("/");
const fileName = aFullPath.pop();
const filePath = aFullPath.join("/");
const filePath = aFullPath.join("/") + "/";
return { ...file, recordId: cur.id, fileName, filePath };
})
);
......@@ -204,11 +216,12 @@ export default {
* 这个函数的目的是在一定条件下,通过持续轮询来执行上传记录的操作。它检查一个队列(snapshot)的大小。如果队列为空,它会等待十分钟(1000 毫秒 * 60 秒 * 10 分钟)后再次检查。如果队列中有记录,它会取出一条记录并上传它。
*/
polling() {
console.log(this.snapshot.size, "this.snapshot.size");
if (this.snapshot.size == 0) {
this.enQueue();
setTimeout(() => {
this.polling();
}, 1000 * 60 * 10);
}, 1000 * 6);
} else {
const record = this.snapshot.dequeue();
this.uploadRecord(record);
......
......@@ -35,3 +35,4 @@ class Queue {
this._items = [];
}
}
export default Queue;
import { storageApi } from "./cache";
import { getFileSaveFolderOnClient, uuid } from "./utils";
import utils from "./utils";
/**
* 记录管理器类
* 用于管理记录列表
......@@ -10,7 +10,7 @@ class RecordManager {
* 用于初始化 RecordManager 实例
*/
constructor() {
this.fileSaveFolderOnClient = getFileSaveFolderOnClient();
// this.fileSaveFolderOnClient = utils.getFileSaveFolderOnClient();
}
// 单例模式
static instance = null;
......@@ -59,7 +59,7 @@ class RecordManager {
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
const records = this.getRecords();
const records = this.getRecords() || [];
records.push(record);
this.setRecords(records);
return records;
......@@ -124,21 +124,23 @@ class RecordManager {
async compatible() {
const unlock = await this.lock();
let path = await utils.getFileSaveFolderOnClient();
try {
let records = this.getRecords();
records.forEach((i) => {
if (i.recordUrlList && i.recordUrlList.length) {
i.recordUrlList.forEach((j) => {
i.recordUrlList.forEach(async (j) => {
if (!j.file.startsWith("file://")) {
const fileName = j.file.split("/").pop();
j.file = this.fileSaveFolderOnClient + fileName;
j.file = path + fileName;
}
});
}
if (!i.id) {
i.id = uuid();
i.id = utils.uuid();
}
});
console.log(records);
this.setRecords(records);
} catch (e) {
throw e;
......
......@@ -90,34 +90,36 @@ var isNetWork = function () {
});
});
};
var uuid = function(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [], i;
var uuid = function (len, radix) {
var chars =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
uuid[14] = "4";
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
r = 0 | (Math.random() * 16);
uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
return uuid.join("");
};
/**
* 获取文件系统根目录的完整路径
......@@ -133,8 +135,8 @@ function getFilePath() {
});
});
}
function getFileSaveFolderOnClient(){
const rootPath = getFilePath();
async function getFileSaveFolderOnClient() {
const rootPath = await getFilePath();
return `file://${rootPath}uniapp_save/`;
}
export default {
......@@ -146,5 +148,5 @@ export default {
isNetWork,
uuid,
getFilePath,
getFileSaveFolderOnClient
getFileSaveFolderOnClient,
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!