当前位置: 首页 > article >正文

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

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

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)
        LoadingDialog.showLoading('正在上传视频...')
        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
              LoadingDialog.hide()
        });
        // 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 LoadingDialog from '@lyb/loading-dialog';
import { BusinessError, request } from '@kit.BasicServicesKit';

interface DurationObject {
  duration: number;
}

@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;
  controller: VideoController = new VideoController()

  async uploadVideo(fileName: string) {
    let uploadTask: request.UploadTask
    let uploadConfig: request.UploadConfig = {
      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
          LoadingDialog.hide()
        });
        // 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)
        LoadingDialog.showLoading('正在上传视频...')
        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() {
  
    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, controller: this.controller })
            .width('100%')
            .height(300)
            .borderRadius(10)// .autoPlay(true)// 设置自动播放
            .loop(true)
            .controls(true)
            .onPrepared((e?: DurationObject) => {
              if (e != undefined) {
                LoadingDialog.hide()
                console.info('onPrepared is ' + e.duration)
              }
            })
            .onStart(() => {
              setTimeout(() => { // 使用settimeout设置延迟跳过黑屏阶段
                this.controller.setCurrentTime(1, SeekMode.PreviousKeyframe)
              }, 150)
            })
        }.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;
              LoadingDialog.showLoading('正在加载视频...')
            } else {
              promptAction.showToast({
                message: '请先选择视频文件!',
                duration: 2000
              });
            }

          })
      }.position({ x: 70, y: 730 })
    }
    .padding(20)
    .backgroundColor('#e8eaed')
    .backgroundImage($r('app.media.back'))
    .backgroundImageSize(ImageSize.FILL)
    .height('100%')
    .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])

  }
}


http://www.kler.cn/a/599746.html

相关文章:

  • Android 13系统定制实战:基于系统属性的音量键动态屏蔽方案解析
  • [AI速读]用持续集成(CI)优化芯片验证环境:Jenkins与EDA工具的实战指南
  • 【Linux学习笔记】gcc编辑器和动静态库的深度剖析
  • SAP-ABAP:SAP事务码SE14深度解析:数据库表管理核心工具
  • mysql传统主从模式下,主从中断接续
  • 探究Three.js中模型移动与旋转的交互逻辑
  • venv 和 conda 哪个更适合管理python虚拟环境
  • 内网穿透的应用-本地部署ChatTTS教程:Windows搭建AI语音合成服务的全流程配置
  • LeetCode讲解篇之456. 132 模式
  • 鸿蒙生态开发
  • OSI 模型详解及详细知识总结
  • C# CancellationTokenSource CancellationToken Task.Run传入token 取消令牌
  • 使用 Nginx 实现镜像流量:提升系统可用性与负载均衡
  • 深入剖析ReLU激活函数:特性、优势与梯度消失问题的解决之道,以及Leaky ReLU 和 Parametric ReLU
  • WordPress分类目录绑定二级域名插件
  • 【Vitis AI】FPGA设备使用PyTorch 运行 ResNet18获得10000fps
  • 制作PaddleOCR/PaddleHub的Docker镜像
  • L2-052 吉利矩阵
  • 从双指针到单调栈,深挖“接雨水”的算法奥秘
  • 价值流映射(Value Stream Mapping):从流程可视化到敏捷效能革命