当前位置: 首页 > article >正文

鸿蒙中拍照上传与本地图片上传

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.图片资源


http://www.kler.cn/a/411774.html

相关文章:

  • JavaWeb--JDBC
  • 如何搭建一个小程序:从零开始的详细指南
  • 过滤条件包含 OR 谓词,如何进行查询优化——OceanBase SQL 优化实践
  • C++设计模式-中介者模式
  • 【31-40期】从Java反射到SSO:深度解析面试高频问题
  • 17. 【.NET 8 实战--孢子记账--从单体到微服务】--记账模块--主币种设置
  • qt 读写文本、xml文件
  • 0 基础 入门简单 linux操作 上篇 利用apt命令装13 linux搭建自己的服务器
  • 【WEB开发.js】getElementById :通过元素id属性获取HTML元素
  • SpringMVC框架---SpringMVC概述、入门案例、常用注解
  • Flink Transformation-转换算子
  • C++设计模式之组合模式的基本结构
  • 【多线程-第一天-多线程的技术方案-pthread演示 Objective-C语言】
  • React中事件处理和合成事件:理解与使用
  • [RabbitMQ] 保证消息可靠性的三大机制------消息确认,持久化,发送方确认
  • 写个添加球队和展示球队的功能--laravel与inertia
  • 多线程
  • 【含开题报告+文档+PPT+源码】基于Spring Boot+Vue的在线学习平台的设计与实现
  • 多级反馈队列调度算法
  • kafka生产者和消费者命令的使用