HarmonyOS 中心仓axios库上传文件时FormData如何支持MultipartFile

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

参考demo:

import { picker } from '@kit.CoreFileKit'
import fs from '@ohos.file.fs';
import { Context } from '@kit.AbilityKit';
import fileUri from "@ohos.file.fileuri";
import axios, { AxiosProgressEvent, AxiosRequestConfig, AxiosResponse, FormData } from '@ohos/axios';
// import { HttpResponseModel } from '../core/network/config';

class HttpResponseModel{

}

@Entry
@Component
struct UploadPage {
  @State imageUrl: string = ''
  private context: Context = getContext(this)

  async executeUpload(filename: string) {
    let internalUri = `internal://cache/${filename}`;
    console.error('internal uri is:' + internalUri)

    let formData = new FormData()
    formData.append('file', internalUri)
    //formData.append('type', 1)
    let request: AxiosRequestConfig<FormData> = {
      url: 'input your url',
      headers:
      {
        'Accept': '/',
        'Content-Type': 'multipart/form-data',
      },
      method: "post",
      context: this.context,
      data: formData,
      onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
        console.error(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
      }
    }
    try {
      let resp: AxiosResponse<HttpResponseModel> =
        await axios.request<HttpResponseModel, AxiosResponse<HttpResponseModel>, FormData>(request)
    } catch (e) {
      console.error(e)
    }
  }
  build() {
    Column() {
      Image(this.imageUrl).width(100).height(100).backgroundColor('#F00')
      Button('select photo from gallery').onClick(async () => {
        let photoSelectOptions = new picker.PhotoSelectOptions();
        photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE
        photoSelectOptions.maxSelectNumber = 1
        let uris: Array<string> = [];
        const photoViewPicker = new picker.PhotoViewPicker()
        let ctx = getContext(this)
        console.error(ctx.cacheDir)
        console.error(ctx.filesDir)
        let photoSelectResult = await photoViewPicker.select(photoSelectOptions)
        uris = photoSelectResult.photoUris;
        // 也可以换成已经拿到的图库图片uri
        let tmp_imageUri = uris[0]
        console.error('select image uri:$tmp_imageUri')
        // 1. 复制文件到沙箱
        fs.open(tmp_imageUri, (err, file) => {
          if (err) {
            console.error("file open failed with error message: " + err.message + ", error code: " + err.code);
          } else {
            let filename = '111.jpg'
            let filepath = this.context.cacheDir + '//' + filename;
            console.error('filename is:' + filename + ', file path is:' + filepath)
            fs.copyFile(file.fd, filepath, () => {
              // /data/storage/el2/base/haps/entry/cache/111.jpg
              this.imageUrl = fileUri.getUriFromPath(filepath)
              // start upload task
              this.executeUpload(filename)
            });
          }
        })
      })
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS三方中心在哪里查询
17浏览 • 1回复 待解决
HarmonyOS axios上传文件失败
37浏览 • 1回复 待解决
ohpm私找不到中心仓库的
345浏览 • 1回复 待解决
三方中心的reflect-metadata问题
1452浏览 • 1回复 待解决
HarmonyOS axios如何上传图片
33浏览 • 1回复 待解决
HarmonyOS axios如何上传多张图片
29浏览 • 1回复 待解决
HarmonyOS HSP共享包上传问题
100浏览 • 1回复 待解决
HarmonyOS 如何使用Axios框架上传图片
64浏览 • 1回复 待解决
HarmonyOS 有关中心 socket-io的问题
141浏览 • 1回复 待解决
HarmonyOS 如何上传文件
168浏览 • 1回复 待解决
使用axios上传图片时候错误
251浏览 • 1回复 待解决
上传har包的具体规范是什么
834浏览 • 1回复 待解决
鸿蒙是否支持多应用共
789浏览 • 1回复 待解决
HarmonyOS 如何通过SFTP上传文件
30浏览 • 1回复 待解决