前面是将文件上传到webgl进程,本篇是将文件从webgl进程中下载文件到浏览器的下载目录中。
通用,只需要 二进制数组和文件名。
一、修改__Internal.jslib
添加一段代码
mergeInto(LibraryManager.library, { BinFileDownloader: function (str, fn ,type) { console.log("start download"); var msg = Pointer_stringify(str); var fname = Pointer_stringify(fn); var contentType = Pointer_stringify(type); function fixBinary(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } console.log("恢复二进制完成"); return buf; } //atob解码使用base64编码的字符串 var binary = fixBinary(atob(msg)); console.log("创建blog数据"); var data = new Blob([binary], { type: contentType }); //创建一个html dom用于触发blob下载 var link = document.createElement('a'); link.download = fname; link.innerHTML = 'DownloadFile'; link.setAttribute('id', 'DownloaderLink'); link.href = window.URL.createObjectURL(data); link.onclick = function () { console.log("模拟点击"); var child = document.getElementById('DownloaderLink'); child.parentNode.removeChild(child); }; link.style.display = 'none'; document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(link.href); }});
解释:接收三个字符串:由文件二进制转换出来的二进制字符串、xxx.yy文件名、文件类型。
统一经过Pointer_stringify转化为js字符串,定义恢复二进制数组函数并调用,创建blob数据块,根据文件类型字符串指定类型(这里要查找contentType);接着创建html的点击下载文件的元素,定义点击功能,模拟点击,点击完成后移除该动态创建的节点避免误触。
二、调用
已导出电子表格为例,在ui中弄个按钮挂载:
using System.Collections;using System.Collections.Generic;using System.IO;using System.Runtime.InteropServices;using UnityEngine;using UnityEngine.UI;public class ExportExlBtn : MonoBehaviour{ // Start is called before the first frame update void Start() { transform.GetComponent<Button>().onClick.AddListener(DownloadFileByURL); } [DllImport("__Internal")] private static extern void BinFileDownloader(string str, string fn,string type); /// <summary> /// 传入二进制数据转二进制字符串 /// </summary> /// <param name="binData"></param> /// <param name="fileName"></param> private void DownloadFileByBin(byte[] binData, string fileName) { if (binData != null) { Debug.Log("Downloading..." + fileName); //将二进制数据转化为js可识别的Base64String BinFileDownloader(System.Convert.ToBase64String(binData), fileName,"application/vnd.ms-excel"); } } public void DownloadFileByURL() { Debug.Log("导出按钮"); if (Application.platform == RuntimePlatform.WebGLPlayer) { FileInfo curFileInfo = new FileInfo(FindObjectOfType<LoadExlBtn>().fileFullPath); Debug.Log("已获取文件1,打开文件流"); FileStream fs = curFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); byte[] buffer = new byte[fs.Length]; int res=fs.Read(buffer, 0, buffer.Length); Debug.Log("已读取"+res+"字节"); if (buffer.Length>0) { DownloadFileByBin(buffer,curFileInfo.Name); }else{ Debug.LogError("不得了"); } } }}
三、参考文件格式
https://www.cnblogs.com/xiaohi/p/6550133.html