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

devtools/2025/4/1 2:43:40/

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

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])}
}

文章来源:https://blog.csdn.net/m0_60880588/article/details/146482139
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/devtools/171079.html

相关文章

力扣DAY24 | 热100 | 回文链表

前言 简单 √ 是反转链表的衍生题&#xff0c;很快写完了。不过没考虑到恢复链表结构的问题。 题目 给你一个单链表的头节点 head &#xff0c;请你判断该链表是否为回文链表。如果是&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 示例 1&#xff1a; 输…

Thinkphp(TP)框架漏洞攻略

Thinkphp5x远程命令执⾏及getshell 环境配置 云服务器&#xff1a;121.40.229.129:8080 靶场&#xff1a;vulhub/thinkphp/5-rce docker-compose up -d #启动环境 访问靶场&#xff1a;http://121.40.229.129:8080/ 远程命令执⾏ http://39.105.61.160:8080/?sindex/thin…

港中文迈向安全的具身AI!EARBench:基础模型在具身AI任务规划中的物理风险评估

作者&#xff1a;Zihao Zhu 1 ^{1} 1, Bingzhe Wu 2 ^{2} 2, Zhengyou Zhang 3 ^{3} 3, Lei Han 3 ^{3} 3, Qingshan Liu 4 ^{4} 4, Baoyuan Wu 1 ^{1} 1单位&#xff1a; 1 ^{1} 1香港中文大学深圳数据科学学院&#xff0c; 2 ^{2} 2腾讯AI实验室&#xff0c; 3 ^{3} 3腾讯机器…

DeepSeek写打台球手机小游戏

DeepSeek写打台球手机小游戏 提问 根据提的要求&#xff0c;让DeepSeek整理的需求&#xff0c;进行提问&#xff0c;内容如下&#xff1a; 请生成一个包含以下功能的可运行移动端打台球小游戏H5文件&#xff1a; 要求 可以重新开始游戏 可以暂停游戏 有白球和其他颜色的球&am…

从技术架构和生态考虑,不是单纯的配置优化,还有哪些方式可以提高spark的计算性能

从技术架构和生态系统层面提升Spark的计算性能&#xff0c;可采取以下核心策略&#xff1a; 一、计算模型重构与执行引擎升级 1. 弹性分布式数据集&#xff08;RDD&#xff09;的血统优化 通过RDD的Lineage&#xff08;血统&#xff09;机制实现容错时&#xff0c;采用增量式…

Linux驱动开发实战之SRIO驱动(二)基于Tsi721驱动

常用驱动介绍 在RapidIO系统中&#xff0c;TSI721是一款常用的RapidIO交换芯片&#xff0c;其驱动程序和相关模块负责管理和优化数据传输&#xff0c;包括DMA&#xff08;直接内存访问&#xff09;操作。以下是您提到的各个模块的作用概述&#xff1a; rapidio.ko: 这是RapidIO…

内网渗透(CSMSF) 构建内网代理的全面指南:Cobalt Strike 与 Metasploit Framework 深度解析

目录 1. Cobalt Strike 在什么情况下会构建内网代理&#xff1f; 2. Cobalt Strike 构建内网代理的主要作用和目的是什么&#xff1f; 3. Cobalt Strike 如何构建内网代理&#xff1f;需要什么条件和参数&#xff1f; 条件 步骤 参数 4. Cobalt Strike 内网代理能获取什…

Jupyter Notebook 常用命令(自用)

最近有点忘记了一些常见命令&#xff0c;这里就记录一下&#xff0c;懒得找了。 文章目录 一、文件操作命令1. %cd 工作目录2. %pwd 显示路径3. !ls 列出文件4. !cp 复制文件5. !mv 移动或重命名6. !rm 删除 二、代码调试1. %time 时间2. %timeit 平均时长3. %debug 调试4. %ru…