HarmonyOS NEXT最新API实现文件上传

ArkTS中api12之后,新增了rcp这个api实现网络请求,进行文件上传比以前好用太多了。随着慢慢的优化,相信鸿蒙会越来越好

import { rcp } from '@kit.RemoteCommunicationKit';
import { picker } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs'
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct UploadPage {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Button("文件上传")
        .onClick(async ()=>{

          let context = getContext(this) as common.Context; // 请确保 getContext(this) 返回结果为 UIAbilityContext
          // 创建文件选择器实例
          const documentViewPicker = new picker.DocumentViewPicker(context);
          let documentSelectOptions = new picker.DocumentSelectOptions();
          documentSelectOptions.maxSelectNumber = 1
          documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4', '.jpg'];
          //选择是否对指定文件或目录授权,true为授权,当为true时,defaultFilePathUri为必选参数,拉起文管授权界面;false为非授权,拉起常规文管界面(可选)
          documentSelectOptions.authMode = true;
          documentViewPicker.select(documentSelectOptions).then(async (documentSelectResult: Array<string>) => {
            let uploadFromFile : rcp.UploadFromFile = {
              fileOrPath : documentSelectResult[0],
            }
            const session = rcp.createSession({
              headers: {
                "content-type": 'multipart/form-data'
              }
            });


            // 文件上传的时候一定要先拷贝一份,然后在进行上传,要不然没权限操作文件
            const context = getContext(this)
            const fileType = 'jpg'
            // (以时间戳)生成一个新的文件名
            const fileName = Date.now() + '.' + fileType
            // 通过缓存路径+文件名 拼接出完整的路径
            const copyFilePath = context.cacheDir + '/' + fileName
            // 将文件 拷贝到 临时目录
            const file = fs.openSync(documentSelectResult[0], fs.OpenMode.READ_ONLY)
            fs.copyFileSync(file.fd, copyFilePath)

            const formFieldFileValue: rcp.FormFieldFileValue = {
              contentType: "image/png",
              remoteFileName: "a.jpg",
              contentOrPath: copyFilePath,
            };

            const formData = new rcp.MultipartForm ({
              'file': formFieldFileValue // file表示服务器端接收的数据的属性名
            })

            // 参数一就是服务器端接口地址
            session.post('http://192.168.15.109:3006/common/upload', formData).then(response=>{
              console.info(`Reponse succeed: ${response}`);
              console.log(JSON.stringify(response.toJSON()))
            }).catch((err: BusinessError)=>{
              console.log(err.message)
            })

            // session.uploadFromFile('http://192.168.15.109:1337/api/v1/common/upload_file', uploadFromFile)
            //   .then(response=>{
            //     console.info(`Reponse succeed: ${response}`);
            //   })
          })


        })
    }
    .height('100%')
    .width('100%')
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容