鸿蒙进行视频上传,使用 request.uploadFile方法

发布于:2025-03-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

一.拉起选择器进行视频选择,并且创建文件名称

async getPictureFromAlbum() {
    // 拉起相册,选择图片
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    // let photoSelectResult: photoAccessHelper.PhotoSelectResult = await
    photoPicker.select(PhotoSelectOptions)
      .then((result) => {
        this.albumPath = result.photoUris[0];
        const fileName = Date.now() + '.' + 'mp4'
        const copyFilePath = this.context.cacheDir + '/' + fileName
        const file = fs.openSync(this.albumPath, fs.OpenMode.READ_ONLY)
        fs.copyFileSync(file.fd, copyFilePath)
        this.isLoading = true;
        this.uploadVideo(fileName)
      })
    // 读取图片为buffer
    // const file = fs.openSync(this.albumPath, fs.OpenMode.READ_ONLY);
    // this.photoSize = fs.statSync(file.fd).size;
    // console.info('Photo Size: ' + this.photoSize);
    // let buffer = new ArrayBuffer(this.photoSize);
    // fs.readSync(file.fd, buffer);
    // fs.closeSync(file);
    //
    // // 解码成PixelMap
    // const imageSource = image.createImageSource(buffer);
    // console.log('imageSource: ' + JSON.stringify(imageSource));
    // this.pixel = await imageSource.createPixelMap({});
  }

二.进行文件上传使用request.uploadFile方法

  • 需要注意的几点事项

  1. files数组里的name字段为后端所需文件key
  2.  监听headerReceive方法可以使你拿到后端接口返回的请求状态,在headers的body里面,只能通过这种方法才能拿到
  3. 如果不需要通过后端去判断状态,可以监听complete,返回code为0的话就使成功状态
  4. 监听progress为当前上传进度
  async uploadVideo(fileName: string) {
    let uploadTask: request.UploadTask
    let uploadConfig: request.UploadConfig = {
      url: '你的url',
      header: { 'Accept': '*/*', 'Content-Type': 'multipart/form-data' },
      method: "POST",
      //name 为后端需要的字段名,为key  type不指定的话截取文件后缀
      files: [{
        filename: 'file',
        name: 'video',
        uri: `internal://cache/${fileName}`,
        type: ""
      }],
      // data为其他所需参数
      data: [],
    };
    try {
      request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
        uploadTask = data;
        uploadTask.on("progress", (size, tot) => {
          console.log('123212' + JSON.stringify(`上传进度:${size}/${tot}\r\n`))
        })
        // 监听这个为  后端所返回的请求信息
        uploadTask.on('headerReceive', (headers: object) => {
          let bodyStr: string = headers["body"]
          let body: ESObject = JSON.parse(bodyStr)
          console.info("upOnHeader headers:" + JSON.stringify(body));
          this.resultPath = body.video_url
          this.isLoading = false;
        });
        // uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
        //   for (let i = 0; i < taskStates.length; i++) {
        //     console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
        //   }
        // });
        // uploadTask.on('fail', (taskStates: Array<request.TaskState>) => {
        //   for (let i = 0; i < taskStates.length; i++) {
        //     console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
        //   }
        // });
      }).catch((err: BusinessError) => {
        console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
      });
    } catch (err) {
      console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
    }
  }

三.完整代码

这里加了个loading状态,不需要可以自行删除

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State getAlbum: string = '显示相册中的图片';
  @State pixel: image.PixelMap | undefined = undefined;
  @State albumPath: string = '';
  @State resultPath: string = '';
  @State photoSize: number = 0;
  @State result: boolean = false;
  private context: Context = getContext(this);
  @State isLoading: Boolean = false;

  async uploadVideo(fileName: string) {
    let uploadTask: request.UploadTask
    let uploadConfig: request.UploadConfig = {
      url: '你的url',
      header: { 'Accept': '*/*', 'Content-Type': 'multipart/form-data' },
      method: "POST",
      //name 为后端需要的字段名,为key  type不指定的话截取文件后缀
      files: [{
        filename: 'file',
        name: 'video',
        uri: `internal://cache/${fileName}`,
        type: ""
      }],
      // data为其他所需参数
      data: [],
    };
    try {
      request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
        uploadTask = data;
        uploadTask.on("progress", (size, tot) => {
          console.log('123212' + JSON.stringify(`上传进度:${size}/${tot}\r\n`))
        })
        // 监听这个为  后端所返回的请求信息
        uploadTask.on('headerReceive', (headers: object) => {
          let bodyStr: string = headers["body"]
          let body: ESObject = JSON.parse(bodyStr)
          console.info("upOnHeader headers:" + JSON.stringify(body));
          this.resultPath = body.video_url
          this.isLoading = false;
        });
        // uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
        //   for (let i = 0; i < taskStates.length; i++) {
        //     console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
        //   }
        // });
        // uploadTask.on('fail', (taskStates: Array<request.TaskState>) => {
        //   for (let i = 0; i < taskStates.length; i++) {
        //     console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
        //   }
        // });
      }).catch((err: BusinessError) => {
        console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
      });
    } catch (err) {
      console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
    }
  }

  async getPictureFromAlbum() {
    // 拉起相册,选择图片
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    // let photoSelectResult: photoAccessHelper.PhotoSelectResult = await
    photoPicker.select(PhotoSelectOptions)
      .then((result) => {
        this.albumPath = result.photoUris[0];
        const fileName = Date.now() + '.' + 'mp4'
        const copyFilePath = this.context.cacheDir + '/' + fileName
        const file = fs.openSync(this.albumPath, fs.OpenMode.READ_ONLY)
        fs.copyFileSync(file.fd, copyFilePath)
        this.isLoading = true;
        this.uploadVideo(fileName)
      })
    // this.albumPath = photoSelectResult.photoUris[0];
    // 读取图片为buffer
    // const file = fs.openSync(this.albumPath, fs.OpenMode.READ_ONLY);
    // this.photoSize = fs.statSync(file.fd).size;
    // console.info('Photo Size: ' + this.photoSize);
    // let buffer = new ArrayBuffer(this.photoSize);
    // fs.readSync(file.fd, buffer);
    // fs.closeSync(file);
    //
    // // 解码成PixelMap
    // const imageSource = image.createImageSource(buffer);
    // console.log('imageSource: ' + JSON.stringify(imageSource));
    // this.pixel = await imageSource.createPixelMap({});
  }

  build() {
    Stack() {
      if (this.isLoading) {
        Column() {
          LoadingProgress()
            .color(Color.White)
            .width(80).height(80)
          Text('努力加载中..')
            .fontSize(16)
            .fontColor(Color.White)
        }
        .width('100%')
        .height('100%')
        .backgroundColor('#40000000')
        .justifyContent(FlexAlign.Center)
      } else {
        Column() {
          Column() {
            if (this.albumPath) {
              Row() {
                Text('需上传视频:').fontSize(20).fontWeight(500).decoration({
                  type: TextDecorationType.Underline,
                  color: Color.Black,
                  style: TextDecorationStyle.SOLID
                })
              }.width('100%').margin({ bottom: 10 })

              Video({ src: this.albumPath })
                .borderRadius(5)
                .width('100%')
                .height(300)
            }
          }
          .padding(10).borderRadius(10)
          .backgroundColor('white')
          .width('100%')

          if (this.result && this.resultPath) {
            Column() {
              Row() {
                Text('已返回结果:').fontSize(20).fontWeight(500).decoration({
                  type: TextDecorationType.Underline,
                  color: Color.Black,
                  style: TextDecorationStyle.SOLID
                })
              }.width('100%').margin({ bottom: 10 })

              Video({ src: this.resultPath })
                .width('100%')
                .height(300)
                .borderRadius(10)
            }.margin({ top: 15 }).padding(10).borderRadius(10)
            .backgroundColor('white')
          }
          Row() {
            Button('选择文件', { type: ButtonType.Normal, stateEffect: true })
              .borderRadius(8)
              .backgroundColor(0x317aff)
              .width(90)
              .onClick(() => {
                this.getPictureFromAlbum();
              })
              .margin({ right: 20 })
            Button('显示视频', { type: ButtonType.Normal, stateEffect: true })
              .borderRadius(8)
              .backgroundColor(0x317aff)
              .width(90)
              .onClick(() => {
                if (this.resultPath) {
                  this.result = true;
                } else {
                  promptAction.showToast({
                    message: '请先选择视频文件!',
                    duration: 2000
                  });
                }

              })
          }.position({ x: 70, y: 730 })
        }
        .padding(20)
        .backgroundColor('#e8eaed')
     
        .height('100%')
        .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.White)

  }
}