HarmonyOS 上传文件跟上传图片的功能如何实现,请提供一个可运行的demo

HarmonyOS
19h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

文件上传:

场景一:系统文件上传至服务器

官网文档地址:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5

注意:官网文档示例代码中的uri: ‘internal://cache/test.txt’直接替换成实际的地址,比如’file://media/Photo/25/IMG_1713972998_021/IMG_20240424_233458.jpg’

场景二:web组件实现文件上传

可参考官网文档的示例代码进行功能实现

官网文档地址:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/web-file-upload-V5?catalogVersion=V5

图片上传:

场景一:图库选择图片上传

import { BusinessError } from '@ohos.base';
import { rcp } from '@kit.RemoteCommunicationKit';
import { picker } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs';
import { http } from '@kit.NetworkKit';
let uploadUrl: string = 'http://192.168.62.4:8080/upload';

 function example01(): string {
  let uri = '';
  let photoViewPicker = new picker.PhotoViewPicker();
  let photoSelectOption = new picker.PhotoSelectOptions();
  photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  photoViewPicker.select(photoSelectOption).then((photoSelectResult) => {
    console.log(" photoSelectResult:" + photoSelectResult);
    uri = photoSelectResult.photoUris[0];
    console.log(" uri:" + uri);
    try {
    let resultPhoto = fs.openSync(uri,fs.OpenMode.READ_ONLY);
      let resultName = resultPhoto.name;
    let fileTemp = fs.openSync(getContext().filesDir+resultPhoto.name,fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE);
      let imageUri = fileTemp.path;
    fs.copyFileSync(resultPhoto.fd,fileTemp.fd);
    fs.closeSync(resultPhoto);
    fs.closeSync(fileTemp);
      const httpRequest = http.createHttp();
      httpRequest.request(uploadUrl,{
        method:http.RequestMethod.POST,
        header:{
          'Content-Type': 'multipart/form-data',
          'Connection':'keep-alive'
        },
        expectDataType:http.HttpDataType.ARRAY_BUFFER,
        multiFormDataList: [
          {
            name:'file',
            contentType: 'image/jpg',
            filePath: imageUri,
            remoteFileName:'file.jpg'
          },
        ],
      },(err,data) => {
        console.log('xxx:上传结束')
        httpRequest.destroy();
      }
      )
  } catch (err) {
     console.error(`tag:Failed to request the upload. err: ${JSON.stringify(err)}`);
   }

  }).catch((err:BusinessError) => {
    console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  })
  return uri;
}
function testRcpMultiPartUpload() {
   example01();
}
function clickget() {
  const session = rcp.createSession();
  session.get("http://192.168.62.4:8080/getText").then((response) => {
    console.log("xxx"+JSON.stringify(response));
  }).catch((err: BusinessError) => {
    console.error("err:" + JSON.stringify(err));
  });
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            testRcpMultiPartUpload();
          })
        Text('getText')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            clickget();
          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

场景二:通过web上传图片

import web_webview from '@ohos.web.webview'
import picker from '@ohos.file.picker'
import { BusinessError } from '@ohos.base'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  //定义一个全局的string类型的数组,用来存放通过picker拉起后选择完图片后图片的uri
  @State uris: Array<string> = []
  aboutToAppear() {
    web_webview.WebviewController.setWebDebuggingAccess(true);
  }
  build() {
    Column() {
      Image(this.uris[0]).width(100).height(100)
      //用来展示选择的图片
      Image(this.uris[1]).width(100).height(100)
      //用来展示选择的视频
      Video({ src: this.uris[0]}).height(100)
      Web({ src: $rawfile('i.html'), controller: this.controller })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .onShowFileSelector((event) => {
          console.log('MyFileUploader onShowFileSelector invoked')
          const photoSelectOptions = new picker.PhotoSelectOptions();
          // 过滤选择媒体文件类型为IMAGE_VIDEO_TYPE
          photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
          // 选择媒体文件的最大数目
          photoSelectOptions.maxSelectNumber = 2; 
          //let uris: Array<string> = [];
          const photoViewPicker = new picker.PhotoViewPicker();
          photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
            this.uris = photoSelectResult.photoUris;
            console.info('photoViewPicker.select to file succeed and uris are:' + this.uris);
          }).catch((err: BusinessError) => {
            console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
          })
          return false
        })
    }
  }
}

html代码:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
    <script>
    window.onload = function() {
      // 获取文件输入元素
      var fileInput = document.getElementById('upload');

      // 监听文件输入的改变事件
      fileInput.addEventListener('change', function(e) {
        // 获取选中的文件
        var file = e.target.files[0];
        // 创建一个FileReader对象
        var reader = new FileReader();

        // 定义文件读取完成后的回调函数
        reader.onloadend = function() {
          // 获取图片元素
          var img = document.getElementById('preview');
          // 将读取到的结果赋值给图片元素的src属性
          img.src = reader.result;
        }

        // 读取文件内容
        if (file) {
          reader.readAsDataURL(file);
        }
      });
    }
  </script>
</head>
<body>
<form id="upload-form" enctype="multipart/form-data">
    <!-- 修改type属性为camera -->
    <input type="file" id="upload" name="upload" accept="video/mp4" capture="camera"/>
    <!-- 添加一个图片元素用于展示图片 -->
    <img id="preview" />
</form>
</body>
</html>
分享
微博
QQ
微信
回复
17h前
相关问题
HarmonyOS 如何实现下列功能,请提供demo
509浏览 • 1回复 待解决
HarmonyOS 上传文件demo
21浏览 • 1回复 待解决
rn HarmonyOS可运行demo
32浏览 • 1回复 待解决
HarmonyOS h5 web上传图片文件demo
36浏览 • 1回复 待解决
HarmonyOS如何实现图片上传
544浏览 • 1回复 待解决
HarmonyOS 上传文件相关Demo
555浏览 • 1回复 待解决
如何HarmonyOS实现图片上传功能
258浏览 • 0回复 待解决
Web组件如何实现文件上传功能
448浏览 • 1回复 待解决
HarmonyOS 请提供路由跳转Demo
410浏览 • 1回复 待解决
想要实现一个图片裁剪功能
440浏览 • 1回复 待解决