1.首页ui
import { picker } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { promptAction } from '@kit.ArkUI';
import { cameraCapture } from './utils/CameraUtils';
import { common } from '@kit.AbilityKit';
import { ImageListView } from './view/ImageListView';
import { http } from '@kit.NetworkKit';
const photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 1;
const MAX_SELECT_IMAGE: number = 9;
@Entry
@Component
struct Index {
@State selectedImages: string[] = [];
imageUpload() {
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions)
.then(res => {
const uri = res.photoUris[0]
const context = getContext(this)
const fileType = 'jpg'
const fileName = Date.now() + '.' + fileType
const copyFilePath = context.cacheDir + '/' + fileName
const file = fs.openSync(uri, fs.OpenMode.READ_ONLY)
fs.copyFileSync(file.fd, copyFilePath)
let files: Array<request.File> = [
{
filename: fileName,
type: fileType,
name: 'img',
uri: `internal://cache/${fileName}`
}
]
// 请求接口,这里暂时用提示框代替
AlertDialog.show({ message: JSON.stringify(files) + '' })
// 请求接口
request.uploadFile(context, {
url: '你的url 地址', // url 地址
method: http.RequestMethod.POST, // 请求方法
header: {
// 和接口文档的要求的格式对象
contentType: 'multipart/form-data',
},
files, // 文件信息
data: [] // 额外提交的数据,不能省略
})
.then((res => {
// 获取响应的内容
}))
})
}
async photographUpload() {
if (this.selectedImages.length >= MAX_SELECT_IMAGE) {
promptAction.showToast({ message: '最多只能选择9张图片!' });
return;
}
const image: string = await cameraCapture(getContext(this) as common.UIAbilityContext);
if (image !== "") {
this.selectedImages.push(image);
AlertDialog.show({ message: JSON.stringify(this.selectedImages) })
}
}
build() {
Column() {
Button('选择上传图片').onClick(() => {
this.imageUpload()
})
// 拍照
Column() {
Button('拍照上传').onClick(() => {
this.photographUpload()
})
if (this.selectedImages.length > 0) {
ImageListView({ selectedImages: this.selectedImages, imageEnableDelete: true })
}
}
}
}
}
2.工具类
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { common } from '@kit.AbilityKit';
export class Constants {
/**
* Action of picker.
*/
static readonly ACTION_PICKER_CAMERA: string = "ohos.want.action.imageCapture";
/**
* Key result of picker.
*/
static readonly KEY_RESULT_PICKER_CAMERA: string = "resourceUri";
}
export async function cameraCapture(context: common.UIAbilityContext): Promise<string> {
const result: common.AbilityResult = await context.startAbilityForResult({
action: Constants.ACTION_PICKER_CAMERA,
parameters: {
'supportMultiMode': false,
'callBundleName': context.abilityInfo.bundleName
}
});
if (result.resultCode === 0) {
const param: Record<string, Object> | undefined = result.want?.parameters;
if (param !== undefined) {
const resourceUri: string = param[Constants.KEY_RESULT_PICKER_CAMERA] as string;
return resourceUri;
}
}
return "";
}
3.展示拍照的照片
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ID_IMAGE: string = 'image';
const ID_DELETE: string = 'delete';
@Component
export struct ImageListView {
@State selectedImages: ResourceStr[] = [];
imageEnableDelete: boolean = false;
build() {
List({ space: 10 }) {
ForEach(this.selectedImages, (image: string, index: number) => {
ListItem() {
RelativeContainer() {
Image(image)
.height(100)
.width(100)
.borderRadius(5)
.alignRules({
bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
left: { anchor: "__container__", align: HorizontalAlign.Start }
})
.id(ID_IMAGE + index)
if (this.imageEnableDelete) {
Image($r('app.media.ic_public_close_filled'))
.height(20)
.width(20)
.onClick(() => {
if (this.imageEnableDelete) {
// Delete an image when you click on it
this.selectedImages.splice(index, 1);
}
})
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
right: { anchor: "__container__", align: HorizontalAlign.End }
})
.id(ID_DELETE + index)
}
}
.width(110)
.height(110)
}
})
}
.height(120)
.width("100%")
.padding({
bottom:10
})
.listDirection(Axis.Horizontal)
.alignSelf(ItemAlign.Start)
}
}
4.图片资源