uploadFile.ets
2.5 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
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import fs from '@ohos.file.fs';
import { request, BusinessError } from '@kit.BasicServicesKit';
import preferencesUtils from '../utils/preferences'
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 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() // 选择图片
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
}
}