Commit d9f63898 by 前端

oss上传

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