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

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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-19 17:44:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-19 17:44:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-19 17:44:04       82 阅读
  4. Python语言-面向对象

    2024-01-19 17:44:04       91 阅读

热门阅读

  1. mysql limit

    2024-01-19 17:44:04       57 阅读
  2. 要在Linux上安装Docker Compose和nginx

    2024-01-19 17:44:04       62 阅读
  3. python中json的用法(详细)

    2024-01-19 17:44:04       53 阅读
  4. js indexOf方法的使用

    2024-01-19 17:44:04       48 阅读
  5. 一道使用LinkedList和Stack解决的算法题

    2024-01-19 17:44:04       45 阅读
  6. 6、机器学习之随机森林

    2024-01-19 17:44:04       58 阅读
  7. 1818:红与黑【解析】-------深度优先搜索

    2024-01-19 17:44:04       42 阅读
  8. springboot项目引入onlyoffice多人协同编辑文档

    2024-01-19 17:44:04       63 阅读
  9. 五个常见的 jQuery 面试题

    2024-01-19 17:44:04       46 阅读