有没有HarmonyOS鸿蒙Next中rcp下载视频的完整demo

有没有HarmonyOS鸿蒙Next中rcp下载视频的完整demo 请提供一下rcp下载视频到相册或者公共目录的demo,或者能够下载大于5m视频的demo也行,谢谢!

2 回复

这个有官方的demo. 支持文件下载, 断点续传什么的. 应该符合你的需求.

https://gitee.com/harmonyos_samples/RcpFileTransfer

我用过rcp 下载过几百兆的视频(因为要支持下载过程中取消, 所以没有使用axios).

更多关于有没有HarmonyOS鸿蒙Next中rcp下载视频的完整demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,下载视频可以通过HttpURLConnectionOkHttp等网络库实现。以下是一个简单的示例代码,展示如何使用HttpURLConnection下载视频并保存到本地:

import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class VideoDownloader {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "VideoDownloader");

    public static void downloadVideo(Context context, String videoUrl, String fileName) {
        try {
            URL url = new URL(videoUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            File outputFile = new File(context.getExternalFilesDir(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI), fileName);
            FileOutputStream outputStream = new FileOutputStream(outputFile);

            InputStream inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
            inputStream.close();
            HiLog.info(LABEL, "Video downloaded successfully: " + outputFile.getAbsolutePath());
        } catch (Exception e) {
            HiLog.error(LABEL, "Error downloading video: " + e.getMessage());
        }
    }
}

使用说明:

  1. 权限申请:确保在config.json中申请了ohos.permission.INTERNETohos.permission.WRITE_MEDIA权限。
  2. 调用方法:在需要下载视频的地方调用downloadVideo方法,传入视频的URL和保存的文件名。

注意事项:

  • 该示例仅适用于简单的视频下载任务,实际应用中可能需要处理更多的异常情况和网络状态。
  • 下载大文件时,建议使用异步任务或线程池,避免阻塞主线程。
回到顶部