HarmonyOS 相册选取图片然后上传到服务器的demo

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

参考示例:

import request from '@ohos.request';
import picker from '@ohos.file.picker';
import fs, { ReadOptions } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';

// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;

@Entry
@Component
struct page {

  @State picture: string = '';

  private openPhotoPicker() {
    let photoPicker = new picker.PhotoViewPicker();
    photoPicker.select({ MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE, maxSelectNumber: 1 }, (error, result) => {
      if (result) {
        this.picture = result.photoUris[0]
        result.photoUris.forEach((uri) => {
          let file = fs.openSync(uri,fs.OpenMode.CREATE);
          // 复制文件到缓存目录下
          fs.copyFileSync(file.fd, cacheDir + '/test.jpeg')
          this.uploadImage(['xxx']);
        })
      }
    });
  }

  private uploadImage(paths: string[]) {
    let allFiles = Array<request.File>()
    let header = new Map<Object, string>();
    header.set('key1', 'value1');
    header.set('key2', 'value2');
    for (let i = 0; i < paths.length; i++) {
      let path = paths;
      allFiles[i] = {
        name: "image" + i + ".jpeg",
        filename: "image" + i + ".jpeg",
        uri: paths[i],
        type: "image"
      }
    }
    let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
    let uploadConfig: request.UploadConfig = {
      url: "xxx",
      header: header,
      method: 'POST',
      files: allFiles,
      data: data
    }
    try {
      request.uploadFile(getContext(this), uploadConfig, (error, response) => {
        if (response) {
          response.on('progress', (uploadedSize: number, totalSize: number) => {
            console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
          })
        } else {
          console.log("upload failure: " + error)
        }
      });
    } catch (error) {
      console.log("upload failure: " + error)
    }
  }

  build() {
    Column() {
      Image(this.picture)
        .backgroundColor(Color.Red)
        .width('60%')
        .aspectRatio(16 / 9)
        .onClick(async () => {
          // 1、选择图片
          // 2、存储沙箱
          // 3、文件上传
          this.openPhotoPicker();
        })
    }
    .width('100%')
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 选择图片上传到服务器demo
354浏览 • 1回复 待解决
HarmonyOS 上传图片服务器
13浏览 • 1回复 待解决
HarmonyOS 文件上传服务器问题
546浏览 • 1回复 待解决
HarmonyOS Rcp.post上传图库文件至服务器
550浏览 • 1回复 待解决
HarmonyOS flutter选取相册图片怎么实现
249浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
1041浏览 • 1回复 待解决