WebGL下载文件到本地

1.将文件放在StreamingAssets下(Word,Excel都可以)。

2.场景里新建一个下载按钮DownLoadBtn。

3.新建脚本DownLoadTest.cs,代码如下。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DownLoadTest : MonoBehaviour
{
    public Button downLoadBtn;
    string data = "";
    void Start()
    {
        downLoadBtn = this.GetComponent<Button>();
        downLoadBtn.onClick.AddListener(()=> BtnClick());
    }
  
    private void BtnClick()
    {
        //调用打包后index文件里的TestSend方法
        Application.ExternalCall("TestSend", data);
    }
}

4.将脚本挂载到刚才新建的DownLoadBtn上。

5.打WebGL包,在WebGL包生成的index.html文件里,添加script方法,代码如下。

<script>
    function TestSend(s){
          var elt = document.createElement('a');
          elt.setAttribute('href', 'StreamingAssets/语音识别教程.docx');
          elt.setAttribute('download', '语音识别教程.docx');
          elt.style.display = 'none';
          document.body.appendChild(elt);
          elt.click();
          document.body.removeChild(elt);
    }
</script>

6.浏览器运行WebGL包,点击下载按钮,会出现浏览器下载提示,下载成功。

猜你喜欢

转载自blog.csdn.net/qq_2633600317/article/details/133680765