FireProtectionDetail.ets
6.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { router, promptAction } from '@kit.ArkUI'
import { webview } from '@kit.ArkWeb'
import fs from '@ohos.file.fs';
import { common, Permissions } from '@kit.AbilityKit';
import { AxiosResponse } from '@ohos/axios'
import { getCosKey, cosKeyTest, cosKeyData, uploadVideoOrImg } from '../api/cosKey'
import loadingDialog from '../dialog/LoadingDialog'
import NavHeader from '../components/NavHeader'
import { basePath } from '../utils/baseUrl'
import preferencesUtils from '../utils/preferences'
import { BusinessError, request } from '@kit.BasicServicesKit';
import { cameraPickerImg } from '../utils/uploadFile'
import { reqPermissionsFromUser, checkAccessToken, commonRouterParams } from '../utils/UserAuth'
let routerInfo: commonRouterParams = router.getParams() as commonRouterParams
const context = getContext() as common.UIAbilityContext;
@Entry
@Component
struct FireProtectionDetail {
controller: RichEditorController = new RichEditorController();
options: RichEditorOptions = { controller: this.controller };
@State projectInfo: commonRouterParams = routerInfo
cosKeyStr: string | null =''
relateId: number = 0
permissions: Array<Permissions> = [
'ohos.permission.CAMERA',
'ohos.permission.MICROPHONE',
'ohos.permission.MEDIA_LOCATION'
];
webviewController: webview.WebviewController = new webview.WebviewController()
onPageShow() {
let pathUrl = (router.getParams() as commonRouterParams)?.videoPath || ''
console.log('pathUrl', pathUrl)
if (pathUrl !== '' || pathUrl !== undefined || pathUrl !== null) {
this.uploadMethods(this.cosKeyStr, this.relateId, pathUrl, 'mp4')
}
}
aboutToAppear(): void {
reqPermissionsFromUser(this.permissions, context)
}
// 加载弹窗
loadingController: CustomDialogController = new CustomDialogController({
builder: loadingDialog(),
customStyle: true,
offset: { dx: 0, dy: 0 },
alignment: DialogAlignment.Center,
autoCancel: false
})
// 上传方法
uploadMethods = async (cosKeyStr: string | null, relateId: number, systemPhotoImagePath: string, fileType: string) => {
if(systemPhotoImagePath =='' || systemPhotoImagePath == null || systemPhotoImagePath == undefined){
return promptAction.showToast({ message: '用户取消选择' });
}
let _this = this
_this.loadingController.open()
let cacheDir = getContext().cacheDir // 获取缓存目录
let filetype = fileType // 设置文件类型
let filename = Date.now() + '.' + filetype // 设置文件名称
let fullPath = cacheDir + '/' + filename // 设置文件路径
const file = fs.openSync(systemPhotoImagePath, fs.OpenMode.READ_ONLY) // 打开文件
fs.copyFileSync(file.fd, fullPath) // 复制文件
// 获取直传签名等数据
let directTransferResult: AxiosResponse<cosKeyTest> = await getCosKey(filename);
let directTransferData: cosKeyData = directTransferResult.data.data
if (directTransferData == null) {
promptAction.showToast({ message: 'getStsDirectSign fail' });
return;
}
let cosKey = directTransferData.coskey
// 生成上传的url
let url = directTransferData.preSignedUrl
// 开始上传
try {
let uploadTask = await request.uploadFile(getContext(),{ // 上传图片
url: url, // 请求地址
// 请求头
header:{
"Content-Type": "application/octet-stream"
},
method: "PUT",
files:[{ // 上传文件
filename: filename, // 文件名
type: fileType, // 文件扩展名
name:'file', // 接口参数名
uri:`internal://cache/${filename}` // 缓存目录中的要上传给服务器的图片路径
}],
data:[]
})
// 上传成功
uploadTask.on('complete', async (taskStates: Array<request.TaskState>) => {
_this.loadingController.close()
for (let i = 0; i < taskStates.length; i++) {
let cosKeyArr: string[] = []
if(cosKeyStr !== null && cosKeyStr !== 'null') {
cosKeyArr = cosKeyStr.split(';')
}
cosKeyArr.push(cosKey)
await uploadVideoOrImg({ cosKey: cosKeyArr.join(';'), relateId: relateId })
await _this.webviewController.runJavaScript(`window.setKey(${JSON.stringify(cosKeyArr.join(';'))})`)
_this.loadingController.close()
}
});
// 上传失败
uploadTask.on('fail', (taskStates: Array<request.TaskState>) => {
_this.loadingController.close()
for (let i = 0; i < taskStates.length; i++) {
promptAction.showToast({ message: '上传失败' });
_this.loadingController.close()
}
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
return error
}
}
build() {
Column(){
NavHeader({title: '编写记录信息'})
Web({
src: `${basePath}/report/handle?id=${this.projectInfo.reportId}&pid=${this.projectInfo.projectId}&source=harmony&token=${preferencesUtils.get('XF_TOKEN', '')}`,
controller: this.webviewController,
}).mixedMode(MixedMode.All).javaScriptAccess(true).domStorageAccess(true)
.onConsole((event) => {
let data = event.message.getMessage().replace(/^['"]|['"]$/g, '');
let formatData = data.split('&')
this.cosKeyStr = formatData[1]
this.relateId = parseInt(formatData[2])
if (formatData[0] == '鸿蒙图片上传') {
// 使用相机拍照
cameraPickerImg().then(async systemPhotoImagePath => {
if (systemPhotoImagePath == '' || systemPhotoImagePath == null) {
return promptAction.showToast({ message: '用户取消选择' });
}
this.uploadMethods(this.cosKeyStr, this.relateId, systemPhotoImagePath, 'jpg')
})
} else if(formatData[0] == '鸿蒙视频上传'){
// 使用相机录像
if (checkAccessToken(this.permissions)) {
router.pushUrl({ url: 'pages/CreateCamera', params: this.projectInfo })
}
}
return false
})
}.height('100%').width('100%')
}
}