HarmonyOS 鸿蒙Next使用ohos.request和Axios库文件上传

发布于 1周前 作者 vueper 来自 鸿蒙OS

HarmonyOS 鸿蒙Next使用ohos.request和Axios库文件上传
<markdown _ngcontent-hlp-c237="" class="markdownPreContainer">

文件上传中传入的uri是沙箱文件,需要转换成缓存文件,因为文件上传只支持从缓存文件中去拿。

import axiosUtil from './AxiosConfig'
import { AxiosResponse, AxiosError, AxiosProgressEvent, FormData } from '[@ohos](/user/ohos)/axios'
import { BusinessRspModel, UserInfoUtil } from '[@ohos](/user/ohos)/componentsFeature/Index';
  import { router } from '@kit.ArkUI';
  import fs, { Options } from '[@ohos](/user/ohos).file.fs'; // 导入文件管理模块
  import { Logger } from '../Logger';
  import { FileUtil } from '../FileUtil';
  import { buffer } from '@kit.ArkTS';
  import { BusinessError, request } from '@kit.BasicServicesKit';
  import { Constants } from '../../constants/Constants';
  
  export class AxiosApi {
    //post请求
    static post(url: string, params: Object) {
      return axiosUtil.post<BusinessRspModel, AxiosResponse<BusinessRspModel>, Object>(url, params)
        .then((res: AxiosResponse<BusinessRspModel>) => {
          if (res.data.status.toString() == '10000') {
            let prop: boolean | undefined = AppStorage.get('showforceLoginOutDialog')
            if (!prop) {
              router.pushNamedRoute({
                name: 'DispatchAuthDialogPage'
              })
            }
          }
          return res.data;
        }).catch((err: AxiosError) => {
          return Promise.reject(err);
        })
    }

//通过Axios文件下载
static download(context: Context, downloadUrl: string, name: string) {
  let startTime = new Date().getTime();
  let dirPath = context.filesDir + Constants.filesDir;
  if (!fs.accessSync(dirPath)) {
    fs.mkdirSync(dirPath, true);
  }
  let filePath = dirPath + name
  try {
    //文件是否存在,如果文件已存在,则先删除文件。
    if (fs.accessSync(filePath)) {
      fs.unlinkSync(filePath); //删除文件
    }
  } catch (err) {
    Logger.warn('accessSync:' + err + '')
  }
  return axiosUtil<BusinessRspModel, AxiosResponse<BusinessRspModel>, null>({
    url: downloadUrl,
    method: 'get',
    context: context,
    filePath: filePath,
    onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
      //下载进度
      let downloadProgress = progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0;
      Logger.warn('AxiosApi下载进度:' + downloadProgress + '')
    }
  }).then((res: AxiosResponse<BusinessRspModel>) => {
    Logger.warn("AxiosApi下载成功: " + JSON.stringify(res.data));
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
    let myFileSize = FileUtil.getInstance().myGetFileSize(filePath, fs.OpenMode.READ_ONLY)
    let arrayBuffer = new ArrayBuffer(myFileSize);
    let readLen = fs.readSync(file.fd, arrayBuffer, {
      offset: 0,
      length: myFileSize
    });
    let buf = buffer.from(arrayBuffer, 0, readLen);
    Logger.iLong(`The content of file: ${buf.toString()}`);
    fs.closeSync(file);
    Logger.warn("AxiosApi下载成功:");
    return filePath
  }).catch((err: AxiosError) => {
    Logger.warn("AxiosApi下载错误:" + JSON.stringify(err));
    return ''
  })

}

//通过Axios文件上传(Uristatic upLoad(context: Context, url: string, uri: string) {
  let file = fs.openSync(uri, fs.OpenMode.CREATE);
  // 复制文件到缓存目录下
  fs.copyFileSync(file.fd, context.cacheDir + '/' + FileUtil.getInstance().getFileName(uri))
  let formData = new FormData()
  // ArrayBuffer
  // 读取
  // let file2 = fs.openSync(uri, 0o2);
  // let stat = fs.lstatSync(path);
  // let buf2 = new ArrayBuffer(stat.size);
  // fs.readSync(file2.fd, buf2); // 以同步方法从流文件读取数据。
  // fs.fsyncSync(file2.fd);
  // fs.closeSync(file2.fd);

  //Uri
  formData.append('file', 'internal://cache/' + FileUtil.getInstance().getFileName(uri))
  return axiosUtil.post<BusinessRspModel, AxiosResponse<BusinessRspModel>, FormData>(url, formData, {
    headers: {
      'Accept': '*/*',
      'Content-Type': 'multipart/form-data',
      'Authorization': UserInfoUtil.getAuthorizationToken()
    },
    context: getContext(context),
    onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
      console.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
    },
  }).then((res: AxiosResponse<BusinessRspModel>) => {
    console.info("result" + JSON.stringify(res.data));
    return res.data;
  }).catch((err: AxiosError) => {
    console.error("error:" + JSON.stringify(err));
    return Promise.reject(err);
  })

}

//通过ohos.request文件上传
static upLoad2(context: Context, url: string, uri: string): Promise<boolean> {
  let file = fs.openSync(uri, fs.OpenMode.CREATE);
  // 复制文件到缓存目录下
  fs.copyFileSync(file.fd, context.cacheDir + '/' + FileUtil.getInstance().getFileName(uri))

  return new Promise<boolean>((resolve, reject) => {

    // 上传任务配置项
    let header = new Map<Object, string>();
    header.set('Accept', '*/*');
    header.set('Content-Type', 'multipart/form-data');
    header.set('Authorization', UserInfoUtil.getAuthorizationToken());
    // let files: Array<request.File> = [
    //   { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
    // ]
    let files: Array<request.File> = [
      {
        filename: FileUtil.getInstance().getFileName(uri),
        type: FileUtil.getInstance().getFileType(uri),
        name: FileUtil.getInstance().getName(uri),
        uri: 'internal://cache/test.jpg'
      }
    ]
    let data: Array<request.RequestData> = [{ name: '', value: '' }];
    let uploadConfig: request.UploadConfig = {
      url: url,
      header: header,
      method: 'POST',
      files: files,
      data: data
    }

    // 将本地应用文件上传至网络服务器
    try {
      request.uploadFile(context, uploadConfig)
        .then((uploadTask: request.UploadTask) => {
          uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
            for (let i = 0; i < taskStates.length; i++) {
              console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
            }
          });
        })
        .catch((err: BusinessError) => {
          console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
        })
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  })
}

//通过ohos.request下载文件
static download2(context: Context, downloadUrl: string, name: string) {
  let startTime = new Date().getTime();

  let filesDir = context.filesDir + '/' + name + '.' + FileUtil.getInstance().getFileType(downloadUrl)
  // 获取应用文件路径
  try {
    //文件是否存在
    fs.accessSync(filesDir)
    fs.unlinkSync(filesDir); //删除文件
  } catch (err) {
  }
  try {
    request.downloadFile(context, {
      url: downloadUrl,
      filePath: filesDir
    }).then((downloadTask: request.DownloadTask) => {
      downloadTask.on('complete', () => {
        console.info('download complete');
        let file = fs.openSync(filesDir, fs.OpenMode.READ_WRITE);
        let myFileSize = FileUtil.getInstance().myGetFileSize(filesDir, fs.OpenMode.READ_ONLY)
        let arrayBuffer = new ArrayBuffer(myFileSize);
        let readLen = fs.readSync(file.fd, arrayBuffer);
        let buf = buffer.from(arrayBuffer, 0, readLen);
        Logger.iLong(`The content of file: ${buf.toString()}`);
        fs.closeSync(file);
      })
    }).catch((err: BusinessError) => {
      console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
  }
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 4px; right: 8px; font-size: 14px;">复制</button>

}

</markdown>

关于HarmonyOS 鸿蒙Next使用ohos.request和Axios库文件上传的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
16 回复

用axios 上传文件时遇到 没有文件夹这个问题,图片已经沙箱处理了,在华为上传是没问题的。

[nodict][listfile.cpp:271->FilterFileRes] Failed to scan dir

 [nodict][ecmascript] Pending exception before IsMixedDebugEnabled called in line:3320, exception details as follows:

[nodict]Error: No such file or directory

大佬帮助看下,谢谢了。

有axios上传的例子吗?

文章很好,不错不错

楼主你好

请问 [@kit](/user/kit).BasicServicesKit 这个是啥意思,哪里来的,我DevEco Studio中开发,一直报错找不到这个

import { BusinessError } from '[@kit](/user/kit).BasicServicesKit';

可能是api用的有差别,我是用的是api11,就是preview1,api12也有这个

评论发不了截图,下边发图了。

你好,想请问一下FileUtil.getInstance().getFileName,是使用fileUri获取文件的文件名吗?
上传后台接收不到file,

目前使用原生的equest.agent.create上传文件不执行completed,这是官方的bug,需要自己结束处理

怎么处理?

请问楼主用的axios的版本号是多少

最新版本的

回到顶部