HarmonyOS 如何使用http的multipart/form-data表单的形式上传图片?

如题:HarmonyOS 如何使用http的multipart/form-data表单的形式上传图片?

阅读 536
1 个回答
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import request from '@ohos.request';

// 使用装饰器定义页面组件
@Entry
@Component
struct Index {
  @State imageList: Array<string> = []
  // 状态变量:原始图片的URI
  @State imgOriginal: string = '';
  @State filePath: string = '';
  uploadFileName: string = '';
  // 弹出图片选择器方法
  async openPicker() {
    try {
      // 设置图片选择器选项
      const photoSelectOptions = new picker.PhotoSelectOptions();
      // 限制只能选择一张图片
      photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
      photoSelectOptions.maxSelectNumber = 10;
      // 创建并实例化图片选择器
      const photoViewPicker = new picker.PhotoViewPicker();
      // 选择图片并获取图片URI
      let uris: picker.PhotoSelectResult = await photoViewPicker.select(photoSelectOptions);
      if (!uris || uris.photoUris.length === 0) return;
      console.info('123123uris', JSON.stringify(uris))
      this.imageList = uris.photoUris
      // 获取选中图片的第一张URI
      let uri: string = uris.photoUris[0];
      // 更新状态变量:保存原始图片的URI
      this.imgOriginal = uri;
      // uris.photoUris.forEach(item =>{
      // 打开文件读取流
      let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
      // 获取当前上下文
      let context = getContext(this) as common.UIAbilityContext;
      // 新建一个保存裁剪后图片的路径
      this.uploadFileName = new Date().getTime() + '.jpg';
      this.filePath = context.cacheDir + '/' + this.uploadFileName;
      // 复制图片到新的路径
      fs.copyFileSync(file.fd, this.filePath);
      // 关闭文件读取流
      fs.closeSync(file);
      console.info('123123filePath', JSON.stringify(this.filePath))
      // })
    } catch (e) {
      console.error('openPicker', JSON.stringify(e));
    }
  }
  //标准记事,资质证明文件,门到站站到门,运输信息(集装箱,整车)
  upPicker() {
    let uploadConfig: request.UploadConfig = {
      url: `internal://cache/${this.uploadFileName}`, type: 'jpg' },
      header: {
        'Accept': '*/*',
        'Content-Type': 'multipart/form-data',
      },
      method: 'POST',
      files: [
      { filename: 'test', name: 'file', uri: internal://cache/${this.uploadFileName}, type: 'jpg' }
        ],
        data: []
      }
    console.log('uploadConfig', JSON.stringify(uploadConfig))
    try {
      request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
        console.log('123123', JSON.stringify(data))
        let uploadTask = data
        let upCompleteCallback = (taskStates:Array<request.TaskState>) =>{
          for (let index = 0; index < taskStates.length; index++) {
            console.info('upCompleteCallback',JSON.stringify(taskStates[index]))
          }
        }
        uploadTask.on('complete',upCompleteCallback)
        let upFailCallback = (taskStates:Array<request.TaskState>) =>{
          for (let index = 0; index < taskStates.length; index++) {
            console.info('upFailCallback',JSON.stringify(taskStates[index]))
          }
        }
        uploadTask.on('fail',upFailCallback)
      })
    } catch (err) {
      console.log('987err', JSON.stringify(err))
    }
  }
  // 构建UI界面
  build() {
    Column() {
      // 添加选择图片按钮,点击后调用打开图片选择器方法
      Button('选择图片→').onClick(() => {
        this.openPicker();
      });
      Image(this.imgOriginal)
        .width('100%')
        .objectFit(ImageFit.Contain);
      Button('&#19978;&#20256;&#22270;&#29255;').onClick(() =&gt; {
        this.upPicker();
      });
    }
    .width('100%');

  }
}
logo
HarmonyOS
子站问答
访问
宣传栏