HarmonyOS 系统相册选一张照片,然后上传到服务器(有编辑功能最好)

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

在拿到arraybuffer后,可以通过file.fs将其写入到本地路径。

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fs-V5#fswrite

拿到本地路径后,就可以通过request.uploadFile将文件上传到服务器了。

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#requestuploadfile9

PhotoViewPicker中拿到uri后需要将图片缓存在cache中读取上传

import request from '@ohos.request';
import picker from '@ohos.file.picker';
import fs 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 Index4 {
  private openPhotoPicker() {
    let photoPicker = new picker.PhotoViewPicker();
    photoPicker.select({
      MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
      maxSelectNumber: 1
    }, (error, result) => {
      if (result) {
        result.photoUris.forEach((uri) => {
          let file = fs.openSync(uri, fs.OpenMode.CREATE);
          // 复制文件到缓存目录下
          fs.copyFileSync(file.fd, cacheDir + '/test.jpeg')
          this.uploadImage(['internal://cache/test.jpeg']);
        })
      }
    });
  }

  private uploadImage(paths: string[]) {
    let allFiles = Array<request.File>()
    let header = new Map<Object, string>();
    header.set('Content-Type', 'multipart/form-data');
    header.set('key2', 'value2');
    for (let i = 0; i < paths.length; i++) {
      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: "http://XXX",
      header: header,
      method: 'POST',
      files: allFiles,
      data: data
    }
    try {
      request.uploadFile(getContext(this), uploadConfig, (error, uploadTask) => {
        if (uploadTask) {
          uploadTask.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() {
    Stack() {
      Column() {
      }
    }
    .width('100%')
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 文件上传服务器问题
350浏览 • 1回复 待解决
如何保存一张PNG图片到相册
1855浏览 • 1回复 待解决
鸿蒙系统类似苹果的服务器吗?
9172浏览 • 1回复 待解决
centos服务器系统宕机
2089浏览 • 1回复 待解决
HarmonyOS Rcp.post上传图库文件至服务器
291浏览 • 1回复 待解决
服务器如何安装双centos系统?
2146浏览 • 1回复 待解决