import picker from '@ohos.file.picker';
@Entry
@Component
//图片选取
struct initOrder{
//上传图片接口
updateImageRequest(uris:Array<string>){
let url:string = 'https://www.baidu.com' //用户请求的url
upLoadImageConfig(url, uris).then((task)=>{
task.on('progress', (progress:request.agent.Progress)=>{
//订阅任务进度事件
})
task.on('completed', (progress:request.agent.Progress)=>{
//订阅任务完成事件
//值得注意的是后台返回的数据会在此回调返回, 并且在请求header中添加Accept-Encoding参数的话返回的数据会乱码
if (progress.extras != undefined) {
//后台返回的数据
let data:string = progress.extras['body'] as string
let model:Record<string, string> = JSON.parse(data)
console.log(JSON.stringify(model))
}
})
task.on('failed', (progress:request.agent.Progress)=>{
//订阅任务失败事件
})
task.on('pause', (progress:request.agent.Progress)=>{
//订阅任务暂停
})
task.on('resume', (progress:request.agent.Progress)=>{
//订阅任务恢复事件
})
task.on('remove', (progress:request.agent.Progress)=>{
//订阅任务删除事件
})
task.start() //这句话很重要 忘记写的话会不执行此接口
})
}
build(){
Column(){
Button("selectetImg")
.onClick(()=>{
examples(1)?.then((imgRequest)=>{
imgRequest.photoUris.forEach(async (element:string)=>{
//在这里进行一些图片的操作, 如图片压缩等...
console.log(element)
})
})
})
}.width('100%')
}
}
//参数 选取图片个数
export function examples(index:number){
try {
let photoSelecOptions = new picker.PhotoSelectOptions()
photoSelecOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE
photoSelecOptions.maxSelectNumber = index
let photoPicker = new picker.PhotoViewPicker();
return photoPicker.select(photoSelecOptions)
} catch (err) {
return null
}
}
//创建上传图片参数class
class updateClass implements request.agent.FormItem
{
name: string = ''
value: string | request.agent.FileSpec | request.agent.FileSpec[]
constructor() {
this.value = ''
}
}
//图片上传
/*
*参数1 请求地址
*参数2 需上传的图片
*值得一提的是, 鸿蒙版上传下载方法的底层逻辑是多个请求, 也就是说上传多张图片的时候, 会执行多次接口
*/
export function upLoadImageConfig(urls:string, photoUris: Array<string>){
let dataArray:Array<request.agent.FormItem> = []
// 默认参数 根据后台参数需要自行填写
let tempDic:Record<string, string> = {
'api':'Harmony',
'ysApp':'yx_harmony',
'name':'img',
'filename':'MyAvatar.jpg',
'Content-Type':'image/jpeg'
}
for (let element of Object.entries(tempDic)) {
const key = element[0]
const value = element[1]
let fromData:updateClass = new updateClass()
fromData.name = key;
fromData.value = value;
dataArray.push(fromData)
}
for (let element of Object.entries(photoUris)) {
let fromData:updateClass = new updateClass()
fromData.name = 'img'
let imgData:request.agent.FileSpec = getImageFileSpec(element[1])
fromData.value = imgData
dataArray.push(fromData)
}
let config:request.agent.Config = {
action:request.agent.Action.UPLOAD,
url:urls,
method:http.RequestMethod.POST,
data:dataArray, //数据
headers:{
'Content-Type': 'multipart/form-data',
}
}
let promise = request.agent.create(getContext(), config)
return promise
}
//参数1: 选取的图片路径地址
function getImageFileSpec(imageuri:string)
{
let fileSpac:request.agent.FileSpec = {
path:imageuri,
}
return fileSpac
}
新人求关注 您的关注是我更新的动力