uploadFile.ets
5.4 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
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import fs from '@ohos.file.fs';
import { request, BusinessError } from '@kit.BasicServicesKit';
import { cameraPicker as picker, camera } from '@kit.CameraKit';
import { common } from '@kit.AbilityKit';
import preferencesUtils from '../utils/preferences'
import { promptAction } from '@kit.ArkUI'
import { fileIo, fileUri } from '@kit.CoreFileKit'
import { VideoCompressor, CompressQuality, CompressorResponseCode } from '@ohos/videocompressor'
let mContext = getContext(this) as common.Context;
export interface uploadResult {
code?: number
msg?: string
fileName?: string
newFileName?: string
url: string
originalFilename?: string
}
// 选择一张图片
export async function selectImg(){
// 1. 创建参数对象
const opts = new photoAccessHelper.PhotoSelectOptions() // 创建参数对象
opts.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE // 设置MIME类型
opts.maxSelectNumber = 1 // 设置最大选择数量
// 2. 创建选择器对象
const photoPicker = new photoAccessHelper.PhotoViewPicker() // 创建选择器对象
const photos = await photoPicker.select(opts) // 选择图片
return photos.photoUris[0] // 返回图片路径
}
// 使用相机拍照
export async function cameraPickerImg() {
let pathDir = getContext().cacheDir;
let fileName = `${new Date().getTime()}`
let filePath = pathDir + `/${fileName}.tmp`
fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);
let uri = fileUri.getUriFromPath(filePath);
let pickerProfile: picker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
saveUri: uri
};
try {
let result: picker.PickerResult = await picker.pick(getContext(), [picker.PickerMediaType.PHOTO], pickerProfile);
console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
return result.resultUri
} catch (error) {
let err = error as BusinessError;
console.error(`the pick call failed. error code: ${err.code}`);
return ''
}
}
// 使用相机录像
export async function cameraPickerVideo() {
let pathDir = getContext().cacheDir;
let fileName = `${new Date().getTime()}`
let filePath = pathDir + `/${fileName}.tmp`
fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);
let uri = fileUri.getUriFromPath(filePath);
let pickerProfile: picker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
saveUri: uri,
videoDuration: 120
};
try {
let result: picker.PickerResult = await picker.pick(getContext(), [picker.PickerMediaType.VIDEO], pickerProfile);
console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
return result.resultUri
} catch (error) {
let err = error as BusinessError;
console.error(`the pick call failed. error code: ${err.code}`);
return ''
}
}
// 视频解码压缩
export async function videoCompressMethod(selectFilePath: string) {
let videoCompressor = new VideoCompressor();
const data = await videoCompressor.compressVideo(getContext(), selectFilePath, CompressQuality.COMPRESS_QUALITY_LOW) // 分别对应3个压缩质量 COMPRESS_QUALITY_HIGH,COMPRESS_QUALITY_MEDIUM, COMPRESS_QUALITY_LOW
if (data.code == CompressorResponseCode.SUCCESS) {
//outputPath: 压缩后的文件地址
console.log("videoCompressor HIGH message:" + data.message + "--outputPath:" + data.outputPath);
return data.outputPath
} else {
console.log("videoCompressor HIGH code:" + data.code + "--error message:" + data.message);
return ''
}
}
// 拷贝图片路径到缓存
export async function copyCachePath(systemPhotoImagePath: string) {
let cacheDir = getContext().cacheDir // 获取缓存目录
let filetype = 'jpg' // 设置图片类型
let filename = Date.now() + '.' + filetype // 设置图片名称
let fullPath = cacheDir + '/' + filename // 设置图片路径
const file = fs.openSync(systemPhotoImagePath, fs.OpenMode.READ_ONLY) // 打开图片
fs.copyFileSync(file.fd, fullPath) // 复制图片
return [fullPath, filename]
}
// 上传图片至服务器
export async function uploadFile() {
// 1. 完成图片上传并获得上传对象
try {
let systemPhotoImagePath = await selectImg() // 选择图片
// let systemPhotoImagePath = await cameraPickerImg() // 使用相机拍照
if(systemPhotoImagePath === '' || systemPhotoImagePath === undefined || systemPhotoImagePath === null) return promptAction.showToast({message: '未选择图片'})
const fileData: string[] = await copyCachePath(systemPhotoImagePath)
let uploader = await request.uploadFile(getContext(),{ // 上传图片
url:'http://xfwbzshd.crgx.net/common/upload', // 请求地址
method:'POST', // 请求方式
// 请求头
header:{
'Content-Type': 'multipart/form-data',
'Authorization': preferencesUtils.get('XF_TOKEN', '') as string
},
files:[{ // 上传文件
filename: fileData[1], // 文件名
type: 'jpg', // 文件扩展名
name:'file', // 接口参数名
uri:`internal://cache/${fileData[1]}` // 缓存目录中的要上传给服务器的图片路径
}],
data:[]
})
return uploader
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
return error
}
}