HarmonyOS鸿蒙Next中需要文件上传的模板代码

HarmonyOS鸿蒙Next中需要文件上传的模板代码 需要文件上传的模板代码

3 回复

请参考:

import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct Page {
  @State message: string = 'Hello World';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('上传').onClick(() => {
          let uploadTask: request.UploadTask;
          let uploadConfig: request.UploadConfig = {
            url: 'http://www.example.com', //需要手动替换为真实服务器地址
            header: { 'Accept': '/' },
            method: "POST",
            files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
            data: [{ name: "name123", value: "123" }],
          };
          try {
            request.uploadFile(getContext(), uploadConfig, (err: BusinessError, data: request.UploadTask) => {
              let headerCallback = (headers: object) => {
                console.info('upOnHeader headers:' + JSON.stringify(headers));
              };
              uploadTask.on('headerReceive', headerCallback);
              if (err) {
                console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
                return;
              }
              uploadTask = data;
            });
          } catch (err) {
            console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
          }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#requestuploadfile9


import { BusinessError } from '@ohos.base';
import { fileUri } from '@kit.CoreFileKit';
import { common, Want, wantConstant } from '@kit.AbilityKit';
import { webview } from '@kit.ArkWeb';
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
@Entry
@Component
export struct Index1 {
  @State message: string = 'Hello World';
  @State controller: WebviewController = new webview.WebviewController()
  delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();
  @State downloadPercent: number = 0;
  @State download: webview.WebDownloadItem = new webview.WebDownloadItem();
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample({
      downloadPercent: this.downloadPercent,
      download:this.download
    }),
    cancel: this.existApp,
    autoCancel: true,
  })
  existApp() {
    this.downloadPercent = 0;
  }
  // 其他应用打开
  openOtherApp() {
    //1、获取resource文件,转成buffer,再传到应用沙箱中,再获取应用沙箱中的路径,并转换为文件URI
    //获取rawfile里的图片arrayBuffer
    let filePath = filesDir + '/上海市场首次公开发行股票网下发行实施细则.pdf'
    let uri = fileUri.getUriFromPath(filePath);
    let want: Want = {
      //配置被分享文件的读写权限,例如对被分享应用进行读写授权
      flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
      // 配置分享应用的隐式拉起规则
      action: 'ohos.want.action.sendData',
      uri: uri,
      type: 'application/pdf'
    }
    context.startAbility(want)
      .then(() => {
        console.info('Invoke getCurrentBundleStats succeeded.');
      })
      .catch((err: BusinessError) => {
        console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
      });
  }
  build() {
    Row() {
      Column() {
        Web({ src: "http://www.chinaclear.cn/zdjs/zzbd/202408/e7ca35158a1f410cb77ac86248a0a14a/files/上海市场首次公开发行股票网下发行实施细则(2024年修订).pdf", controller: this.controller })
          .mixedMode(MixedMode.All)
          .javaScriptAccess(true)
          .multiWindowAccess(false)
          .domStorageAccess(true)
          .allowWindowOpenMethod(true)
          .onControllerAttached(() => {
            try {
              this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
                console.log("will start a download .");
                // 传入一个下载路径,并开始下载。
                webDownloadItem.start(filesDir + '/上海市场首次公开发行股票网下发行实施细则.pdf');
              })
              this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => {
                this.download = webDownloadItem;
                this.downloadPercent = webDownloadItem.getPercentComplete()
              })
              this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
                // 下载失败
                console.log("download failed guid: " + webDownloadItem.getLastErrorCode());
              })
              this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
                this.dialogController?.close()
                this.openOtherApp()
              })
              this.controller.setDownloadDelegate(this.delegate);
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
            }
          })
          .onDownloadStart(()=> {
            this.dialogController?.open()
          })
      }
      .height('100%')
    }
  }
}

@CustomDialog
struct CustomDialogExample {
  controller?: CustomDialogController
  @Link downloadPercent: number;
  @Link download: webview.WebDownloadItem;
  build() {
    Column() {
      Text('下载进度')
        .fontSize(20)
        .height(50)
        .backgroundColor(Color.Blue)
        .width("100%")
        .textAlign(TextAlign.Center)
      Row(){
        Progress({ value: this.downloadPercent, total: 100, type: ProgressType.Linear })
          .width("70%")
          .margin({
            top:50,
            bottom:50,
            right:20
          })
        Text(this.downloadPercent + "%")
      }
      Text("取消下载")
        .fontSize(16)
        .borderWidth(1)
        .borderColor("#ededed")
        .width("100%")
        .height(40)
        .textAlign(TextAlign.Center)
        .onClick(() =>{
          this.download.cancel();
          this.controller?.close()
        })
    }
  }
}

更多关于HarmonyOS鸿蒙Next中需要文件上传的模板代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)Next中,文件上传功能可以通过@ohos.request模块实现。以下是一个简单的文件上传模板代码示例:

import request from '@ohos.request';

async function uploadFile(fileUri: string, uploadUrl: string) {
  try {
    const file = await request.uploadFile({
      url: uploadUrl,
      files: [{ uri: fileUri, name: 'file' }],
    });

    console.log('File upload success:', file);
  } catch (error) {
    console.error('File upload failed:', error);
  }
}

// 使用示例
const fileUri = 'internal://app/file.txt'; // 文件路径
const uploadUrl = 'https://example.com/upload'; // 上传地址
uploadFile(fileUri, uploadUrl);

此代码通过request.uploadFile方法实现文件上传,fileUri为本地文件路径,uploadUrl为服务器上传地址。

在HarmonyOS鸿蒙Next中,文件上传可以通过Http模块和File模块实现。以下是一个简单的文件上传模板代码:

import http from '@ohos.net.http';
import fileio from '@ohos.fileio';

// 创建Http请求对象
let httpRequest = http.createHttp();

// 文件路径
let filePath = 'path/to/your/file.txt';

// 读取文件内容
let fileData = fileio.readTextSync(filePath);

// 创建Http请求选项
let options = {
  method: http.RequestMethod.POST,
  header: {
    'Content-Type': 'multipart/form-data'
  },
  extraData: {
    file: fileData
  },
  expectDataType: http.HttpDataType.STRING
};

// 发送请求
httpRequest.request('https://your-server.com/upload', options, (err, data) => {
  if (err) {
    console.error('Upload failed:', err);
  } else {
    console.log('Upload success:', data.result);
  }
});

代码说明:

  1. http.createHttp():创建HTTP请求对象。
  2. fileio.readTextSync():同步读取文件内容。
  3. http.RequestMethod.POST:设置请求方法为POST。
  4. extraData:包含文件数据的额外请求数据。

注意事项:

  • 确保文件路径正确。
  • 根据服务器要求调整Content-Type和其他请求头。
  • 处理异步请求的异常情况。

这段代码适用于简单的文件上传场景,根据实际需求可能需要进一步调整。

回到顶部