需求:通过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);
}
}
}
以上就是完整的流程和代码内容了。
如有不对或者更好的方法欢迎指教