UnityWebGL screenshot/picture/file call browser download
principle
Code (take downloading pictures as an example)
ImageDownloader.jslib
//ImageDownloader.jslib var ImageDownloaderPlugin = { ImageDownloader: function (str, fn) { console.log("start jslib download"); var msg = Pointer_stringify(str); var fname = Pointer_stringify(fn); var contentType = 'image/jpeg'; 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); } return buf; } //Atob decodes base64 encoded strings var binary = fixBinary(atob(msg)); var data = new Blob([binary], { type: contentType }); //Create an html dom to trigger the blob download var link = document.createElement('a'); link.download = fname; link.innerHTML = 'DownloadFile'; link.setAttribute('id', 'ImageDownloaderLink'); link.href = window. URL.createObjectURL(data); link.onclick = function () { var child = document.getElementById('ImageDownloaderLink'); child.parentNode.removeChild(child); }; link.style.display = 'none'; document.body.appendChild(link); link.click(); window. URL.revokeObjectURL(link.href); } }; //Incorporated into Unity, officially written. mergeInto(LibraryManager.library, ImageDownloaderPlugin)
C # code
[DllImport("__Internal")] private static extern void ImageDownloader(string str, string fn); public void DownloadImage(byte[] imageData, string imageFileName = "newpic") { if (imageData != null) { Debug. Log("Downloading..." + imageFileName); ImageDownloader(System.Convert.ToBase64String(imageData), imageFileName); } }
//TestJPEGDownload.cs using System; using System. Collections; using System. Collections. Generic; using UnityEngine; public class TestJPEGDownload : MonoBehaviour { public Sprite sprite; public UnityEngine. UI. Button button; private void Start() { button.onClick. AddListener(this.onButtonClick); } private void onButtonClick() { byte[] photoByte = getImageSprite();// Get the byte stream of the jpeg image if (photoByte != null) { DownloadImage(photoByte, sprite.name + ".jpg"); }else{ Debug. LogError; } } private byte[] getImageSprite() { if (sprite) { return sprite.texture. EncodeToJPG(); } return null; } }