Unity笔记之WebGL下载图片、视频

需求:通过unity发布出来的webgl在网页上去下载给定路径的视频、图片等。
这里附一下参考的博客
这里面是下载图片的方式。对应的格式的话可以去百度查一下。添加链接描述
在这里插入图片描述

下载视频的话只需要把这里面的
在这里插入图片描述
改成视频对应的就行了。
比如说我这修改后的下载视频的:

我的C#调用代码为:

#region 视频下载
    string path_DownLoad;//地址
    public void ClickDownLoadVideo()
    {
        StartCoroutine(LoadVideo(path_DownLoad));
    }
    IEnumerator LoadVideo(string url)
    {
        Debug.Log(url);
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();
        if (request.isHttpError || request.isNetworkError)
            UnityEngine.Debug.Log(request.error);
        else
        {
            byte[] photoByte = request.downloadHandler.data;//获取视频的字节流

            if (photoByte != null)
                woc.DownloadVideo(photoByte,  "11.mp4");
            else
                Debug.LogError("不得了");
        }
    }
    #endregion
#region 图片下载
    public void ClickDownLoadImage()
    {
        onButtonClick();
    }
    private void onButtonClick()
    {
        byte[] photoByte = getImageSprite();//获取jpeg图像的字节流
        if (photoByte != null)
            woc.DownloadImage(photoByte, image.sprite.name + ".jpg");
        else
            Debug.LogError("不得了");
    }
    private byte[] getImageSprite()//获取图片纹理
    {
        if (image.sprite)
            return image.sprite.texture.EncodeToJPG();
        return null;
    }
    #endregion
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public static class woc 
{
    [DllImport("__Internal")]
    private static extern void ImageDownloader(string str, string fn);
    public static void DownloadImage(byte[] imageData, string imageFileName = "newpic")
    {
        if (imageData != null)
        {
            Debug.Log("Downloading..." + imageFileName);
            ImageDownloader(System.Convert.ToBase64String(imageData), imageFileName);
        }
    }

    [DllImport("__Internal")]
    private static extern void VideoDownloader(string str, string fn);
    public static void DownloadVideo(byte[] videoData, string videoFileName = "newpic")
    {
        if (videoData != null)
        {
            Debug.Log("Downloading..." + videoFileName);
            VideoDownloader(System.Convert.ToBase64String(videoData), videoFileName);
        }
    }
}

以上就是完整的流程和代码内容了。
如有不对或者更好的方法欢迎指教

posted @   一世癫狂  阅读(31)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示