小工具知识网

当前位置: 首页 > 行业知识 > unity webgl 系列(2):从webgl内存中下载文件到本地硬盘

行业知识

unity webgl 系列(2):从webgl内存中下载文件到本地硬盘

2026-11-15 13:19:57 来源:互联网转载

前面是将文件上传到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  

解释:接收三个字符串:由文件二进制转换出来的二进制字符串、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().onClick.AddListener(DownloadFileByURL);    }    [DllImport("__Internal")]    private static extern void BinFileDownloader(string str, string fn,string type);        ///     /// 传入二进制数据转二进制字符串    ///     ///     ///     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().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

 

上一篇:集群服务器怎么同步配置?

下一篇:JVM(垃圾回收机制 ---- GC)