HarmonyOS 从相册中选择图片上传到后端服务器

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

上传下载demo可参考:https://gitee.com/harmonyos_samples/upload-and-down-load,也可参考以下代码片段看下:

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 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&#34',
      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)
    }
  }
}

可以通过订阅订阅上传任务HTTP响应事件来获取对应response

可参考官网文档链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#onheaderreceive7

分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 关于相册中选择图片上传
37浏览 • 1回复 待解决
本机获取图片进行上传到spring后端
2414浏览 • 1回复 待解决
HarmonyOS 文件上传服务器问题
397浏览 • 1回复 待解决
HarmonyOS Rcp.post上传图库文件至服务器
336浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
932浏览 • 1回复 待解决
HarmonyOS如何上传图片到模拟相册
980浏览 • 1回复 待解决