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

HarmonyOS
2024-12-24 16:00:19
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu
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%');

  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
分享
微博
QQ
微信
回复
2024-12-24 16:33:02


相关问题
HarmonyOS POST form-data方式body如何组织?
1261浏览 • 1回复 待解决
http请求如何表单形式进行传输
3873浏览 • 1回复 待解决
HarmonyOS如何实现图片上传
968浏览 • 1回复 待解决
http请求如何以JSON形式进行传输
2890浏览 • 1回复 待解决
HarmonyOS 如何使用Axios框架上传图片
929浏览 • 1回复 待解决