鸿蒙进行视频上传,使用 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.mzph.cn/news/899267.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++ map容器总结

map基本概念 简介&#xff1a; map中所有元素都是pair pair中第一个元素为key&#xff08;键值&#xff09;&#xff0c;起到索引作用&#xff0c;第二个元素为value&#xff08;实值&#xff09; 所有元素都会根据元素的键值自动排序 本质&#xff1a; map/multimap属于关…

【Zookeeper搭建(跟练版)】Zookeeper分布式集群搭建

&#xff08;一&#xff09;克隆前的准备 1. 用 xftp 发送文件 2. 时间同步&#xff1a; sudo cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 3. zookpeeper 安装 部署 呼应开头发送的压缩包&#xff0c;解压&#xff1a; cd ~ tar -zxvf zookeeper-3.4.6.tar.g…

Flutter项目之页面实现以及路由fluro

目录&#xff1a; 1、项目代码结构2、页面编写以及路由配置main.dart(入口文件)page_content.dartindex.dart&#xff08;首页&#xff09;application.dart&#xff08;启动加载类&#xff09;pubspec.yaml&#xff08;依赖配置文件&#xff09;login.dart&#xff08;登录页&…

记录Jmeter 利用BeanShell 脚本解析JSON字符串

下载org.json包(文档说明) #下载地址 https://www.json.org/ # github 地址 https://github.com/stleary/JSON-java # api 文档说明 https://resources.arcgis.com/en/help/arcobjects-java/api/arcobjects/com/esri/arcgis/server/json/JSONObject.htmlBeanShell脚本 import…

uniapp动态循环表单校验失败:初始值校验

问题现象 &#x1f4a5; 在实现动态增减的单价输入表单时&#xff08;基于uv-form组件&#xff09;&#xff0c;遇到以下诡异现象&#xff1a; <uv-input>的v-model绑定初始值为数字类型时&#xff0c;required规则失效 ❌数字类型与字符串类型校验表现不一致 &#x1…

UML 图六种箭头含义详解:泛化、实现、依赖、关联、聚合、组合

目录 一、泛化&#xff08;Generalization&#xff09; 概念 表示方法 二、实现&#xff08;Realization&#xff09; 概念 表示方法 三、依赖&#xff08;Dependency&#xff09; 概念 表示方法 四、关联&#xff08;Association&#xff09; 概念 表示方法 五、…

Android Logcat总结

文章目录 Android Logcat总结日志格式过滤日志正向过滤反向过滤正则过滤日志等级 Android Logcat总结 日志格式 用法&#xff1a; Log.e("TAG", "hello") Log.i("TAG", "hello") Log.d("TAG", "hello")依次为&…

Unity UGUI - 六大基础组件

目录 一、Canvas上 1. Canvas&#xff1a;复制渲染子UI控件 2. ✨Canvas Scaler✨&#xff1a;画布分辨率自适应 3. Graphics Raycaster&#xff1a;射线事件响应 4. ✨Rect Transform✨&#xff1a;UI位置锚点对齐 二、Event System上 5. Event System 6. Standalone …

基于Springboot的网上订餐系统 【源码】+【PPT】+【开题报告】+【论文】

网上订餐系统是一个基于Java语言和Spring Boot框架开发的Web应用&#xff0c;旨在为用户和管理员提供一个便捷的订餐平台。该系统通过简化餐饮订购和管理流程&#xff0c;为用户提供快速、高效的在线订餐体验&#xff0c;同时也为管理员提供完善的后台管理功能&#xff0c;帮助…

css 实现闪烁光标

要实现闪烁光标&#xff08;比如文本输入框内常见的闪烁效果&#xff09;&#xff0c;可以使用 CSS 动画。下面是一个简单的方法&#xff1a; 代码示例 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta n…

从JVM底层揭开Java方法重载与重写的面纱:原理、区别与高频面试题突破

&#x1f31f;引言&#xff1a;一场由方法调用引发的"血案" 2018年&#xff0c;某电商平台在"双十一"大促期间遭遇严重系统故障。 技术团队排查发现&#xff0c;问题根源竟是一个继承体系中的方法重写未被正确处理&#xff0c;导致订单金额计算出现指数级…

详解Spark executor

在 Apache Spark 中&#xff0c;Executor&#xff08;执行器&#xff09; 是运行在集群工作节点&#xff08;Worker Node&#xff09;上的进程&#xff0c;负责执行具体的计算任务并管理数据。它是 Spark 分布式计算的核心组件之一&#xff0c;直接决定了任务的并行度和资源利用…

适配器模式及其典型应用

引言 适配器模式&#xff08;Adapter Pattern&#xff09;是一种结构型设计模式&#xff0c;它允许不兼容的接口协同工作。适配器模式通过创建一个适配器类来转换一个类的接口&#xff0c;使其能够与另一个类的接口兼容。这种模式在实际开发中非常有用&#xff0c;特别是在需要…

如何在 Vue 项目中使用v - for指令进行列表渲染,如何优化其性能?

大白话如何在 Vue 项目中使用v - for指令进行列表渲染&#xff0c;如何优化其性能&#xff1f; 在Vue项目里&#xff0c;咱们常常会碰到要把一组数据渲染成列表的状况。这时候&#xff0c;v-for指令就派上大用场啦&#xff01;它能让咱们轻松地把数据数组里的每个元素渲染成对…

qt QQuaternion详解

1. 概述 QQuaternion 是 Qt 中用于表示三维空间中旋转的四元数类。它包含一个标量部分和一个三维向量部分&#xff0c;可以用来表示旋转操作。四元数在计算机图形学中广泛用于平滑的旋转和插值。 2. 重要方法 默认构造函数 QQuaternion::QQuaternion(); // 构造单位四元数 (1…

如何将爬取的评论数据存储到数据库?

在使用Python爬虫获取1688商品评论后&#xff0c;将这些数据存储到数据库中是一个常见的需求。这样可以方便后续的数据分析、查询和管理。本文将详细介绍如何将爬取的评论数据存储到数据库中&#xff0c;包括MySQL和SQLite两种常见的数据库。 一、准备工作 1. 安装必要的Pytho…

Maven中为什么有些依赖不用引入版本号

先给出一个例子&#xff1a; <parent><artifactId>sky-take-out</artifactId><groupId>com.sky</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>sky-s…

Nginx相关漏洞解析

一、CRLF注入漏洞 原理&#xff1a;Nginx将传入的url进行解码&#xff0c;对其中的%0a%0d替换成换行符&#xff0c;导致后面的数据注入至头部&#xff0c;造成CRLF 注入漏洞 1、开环境 2、访问网站&#xff0c;并抓包 3、构造请求头 %0ASet-cookie:JSPSESSID%3D1 这样就可以…

RUBY报告系统

我们常用GFP及其变体如RFP、YFP、mCherry等作为基因表达的报告蛋白——需要荧光显微镜制片观察&#xff1b;此外还有GUS或荧光素酶作为报告酶——需要添加底物。 RUBY报告系统则与众不同&#xff0c;其作用原理是&#xff1a;将酪氨酸转化为鲜艳的红色甜菜碱&#xff0c;无需使…

[力扣每日一练]关于MySQL和pandas的正则表达式应用

一&#xff1a;题目要求 表&#xff1a;Users-------------------------- | Column Name | Type | -------------------------- | user_id | int | | email | varchar | -------------------------- (user_id) 是这张表的唯一主键。 每一行包含用…