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

鸿蒙进行视频上传,使用 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 = awaitphotoPicker.select(PhotoSelectOptions).then((result) => {this.albumPath = result.photoUris[0];const fileName = Date.now() + '.' + 'mp4'const copyFilePath = this.context.cacheDir + '/' + fileNameconst 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.UploadTasklet 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_urlLoadingDialog.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.UploadTasklet 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_urlLoadingDialog.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 = awaitphotoPicker.select(PhotoSelectOptions).then((result) => {this.albumPath = result.photoUris[0];const fileName = Date.now() + '.' + 'mp4'const copyFilePath = this.context.cacheDir + '/' + fileNameconst 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.mrgr.cn/news/95764.html

相关文章:

  • 大模型应用(Java)2025/3/24
  • LeetCode热题100JS(69/100)第十三天|34|33|153|4|20
  • 2025-3-24 leetcode刷题情况(动态规划——01背包)
  • 【HTML5游戏开发教程】零基础入门合成大西瓜游戏实战 | JS物理引擎+Canvas动画+完整源码详解
  • stm32-IIC
  • 运动仿真——phased.Platform
  • 手动创建Electron+React项目框架(建议直接看最后)
  • 项目日记 -云备份 -服务端配置信息模块
  • Spatial Multiplexing Power Save
  • Spring Boot整合SSE实现消息推送:跨域问题解决与前后端联调实战
  • 排序算法(插入,希尔,选择,冒泡,堆,快排,归并)
  • python-58-基于python的两种方式操作windows安装的pg数据库
  • 【江协科技STM32】Unix时间戳(学习笔记)
  • tortoiseSVN、source insignt、J-flash使用
  • python --face_recognition(人脸识别,检测,特征提取,绘制鼻子,眼睛,嘴巴,眉毛)/活体检测
  • 【MySQL】一篇讲懂什么是聚簇索引和非聚簇索引(二级索引)以及什么是回表?
  • 基于PySide6的CATIA自动化工具开发实战——空几何体批量清理系统
  • 矩阵补充,最近邻查找
  • 流程控制语句
  • 【渗透测试】Fastjson 反序列化漏洞原理(一)