Ejemplo n.º 1
0
    /// ボタンをクリックした時の処理
    public void OnClick()
    {
        // Open file with filter
        var extensions = new [] {
            new ExtensionFilter("VRM Files", "vrm"),
            new ExtensionFilter("All Files", "*"),
        };
        var paths = StandaloneFileBrowser.OpenFilePanel("Open File", "", extensions, true);

        if (paths.Length > 0)
        {
            var file = paths[0];

            byte[] bytes   = FileBrowserHelpers.ReadBytesFromFile(file);
            var    context = new VRMImporterContext();
            try {
                context.ParseGlb(bytes);
                msg.text = "Import VRM finished successfully. (" + file + ")";
                var meta = context.ReadMeta(false); //引数をTrueに変えるとサムネイルも読み込みます
                Debug.LogFormat("meta: title:{0}", meta.Title);
                //同期処理で読み込みます
                context.Load();
                //読込が完了するとcontext.RootにモデルのGameObjectが入っています
                Destroy(instance);
                instance = context.Root;
                instance.transform.position = new Vector3(0, 0, 0);
                instance.transform.rotation = Quaternion.Euler(0, 0, 0);
                instance.AddComponent <PMXExporter>();
                context.ShowMeshes();
            } catch (Exception ex) {
                msg.text = "Error: " + ex.Message;
            }
        }
    }
Ejemplo n.º 2
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: both, Allow multiple selection: true
        // Initial path: default (Documents), Initial filename: empty
        // Title: "Load File", Submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load"));

        // Dialog is closed
        // Print whether the user has selected some files/folders or cancelled the operation (FileBrowser.Success)
        Debug.Log(FileBrowser.Success);

        if (FileBrowser.Success)
        {
            // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
            for (int i = 0; i < FileBrowser.Result.Length; i++)
            {
                Debug.Log(FileBrowser.Result[i]);
            }

            // Read the bytes of the first file via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

            // Or, copy the first file to persistentDataPath
            string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
            FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);
            previewImage.sprite = LoadSprite(destinationPath);
        }
    }
Ejemplo n.º 3
0
    IEnumerator ShowLoadDialogFolderCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(true, null, "Select Folder", "Select"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            sourchPath = FileBrowser.Result;

            string strCh = (characterNo < 10) ? ("0" + characterNo.ToString()) : characterNo.ToString();
            string strFr = (frameNo < 10) ? ("0" + frameNo.ToString()) : frameNo.ToString();

            string outlineFileStr  = "//" + string.Format(outlineFilePrefix, strCh, strFr) + "." + fileSuffix;
            string originalFileStr = "//" + string.Format(originalFilePrefix, strCh, strFr) + "." + fileSuffix;

            var photofileContent   = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result + originalFileStr);
            var outlinefileContent = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result + outlineFileStr);

            photoToSwap.sprite.texture.LoadImage(photofileContent);
            outlineToSwap.sprite.texture.LoadImage(outlinefileContent);
        }
    }
Ejemplo n.º 4
0
    IEnumerator ShowLoadDialogCoroutine(Toggle toggle)
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            byte[]    bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
            Texture2D tex   = new Texture2D(1024, 1024);
            tex.LoadImage(bytes);

            if (tex.height > 1024 || tex.height < 1024 || tex.width > 1024 || tex.width < 1024)
            {
                DisplayError("Invalid Map Height or Length, dimenstion must be 1024x1024");
            }

            if (toggle.group.name == Selection.HeightSelect.ToString())
            {
                customHeightmap = tex;
            }
            else if (toggle.group.name == Selection.SoilSelect.ToString())
            {
                customSoilMap = tex;
            }
            else if (toggle.group.name == Selection.VegetationSelect.ToString())
            {
                customVegetationMap = tex;
            }
        }
    }
Ejemplo n.º 5
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        if (FileBrowser.Success)
        {
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
            AddFile(FileBrowser.Result);
        }
    }
Ejemplo n.º 6
0
    void OpenAndReadFile(string path)
    {
        Debug.Log(path);

        if (path != "")
        {
            Text   tx = GameObject.Find("DebugText").GetComponent <Text>();
            byte[] bt = FileBrowserHelpers.ReadBytesFromFile(path);
            tx.text  = path + "\n";
            tx.text += System.Text.Encoding.ASCII.GetString(bt);
        }
    }
Ejemplo n.º 7
0
        public Sprite LoadSprite(string path)
        {
            byte[]    bytes = new byte[0];
            Texture2D tex   = new Texture2D(2, 2);

            bytes = FileBrowserHelpers.ReadBytesFromFile(path);
            tex.LoadImage(bytes);

            Rect   rec    = new Rect(0, 0, tex.width, tex.height);
            Sprite sprite = Sprite.Create(tex, rec, new Vector2(0.5f, 0.5f), 100);

            return(sprite);
        }
 IEnumerator ShowLoadDialogCoroutine()
 {
     
     yield return FileBrowser.WaitForLoadDialog(false, null, "Select Sound", "Select");
 
     pathText.text = FileBrowser.Result;
 
     if (FileBrowser.Success)
     {
         byte[] SoundFile = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
         yield return SoundFile;
 
         audioSource.clip = NAudioPlayer.FromMp3Data(SoundFile);
         audioSource.Play();   
     }
 }
Ejemplo n.º 9
0
    /// <summary>
    /// Uploads a single file to the server. Not used in case of upload to AmazonS3
    /// Note - As the backend server supports only upload to AmazonS3 this is never called
    /// </summary>
    /// <param name="uploadFilePath">Path of file to be uploaded</param>
    /// <param name="deleteTempFile">Path of temporary Zip file</param>
    /// <returns></returns>
    private IEnumerator UploadFileToServer(string uploadFilePath, bool deleteTempFile)
    {
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
        string fileName = FileBrowserHelpers.GetFilename(uploadFilePath);

        byte[] fileData = FileBrowserHelpers.ReadBytesFromFile(uploadFilePath);
        formData.Add(new MultipartFormFileSection("Object", fileData, fileName, "application/octet-stream"));

        using (UnityWebRequest uwr = UnityWebRequest.Post(amazonS3ServerBackend + "/fileupload", formData))
        {
            uwr.SendWebRequest();

            MessageFields uploadMsgFields = DisplayUploadProgressMessage();
            StartCoroutine(CheckUploadConnection(uwr));
            while (!uwr.isDone)
            {
                string progress = "Progress : " + Mathf.Round(uwr.uploadProgress * 100).ToString() + "%";
                uploadMsgFields.MessageDetails("Upload Progress ...", progress);
                if (uwr.isNetworkError || uwr.isHttpError)
                {
                    yield break;
                }
                yield return(null);
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                DestroyUploadProgressMessage(uploadMsgFields);
                if (deleteTempFile && FileBrowserHelpers.FileExists(uploadFilePath))
                {
                    FileBrowserHelpers.DeleteFile(uploadFilePath);
                    Debug.Log("Temp File deleted after Error");
                }
                DisplayUploadErrorMessage(uwr.error);
            }
            else
            {
                DestroyUploadProgressMessage(uploadMsgFields);
                if (deleteTempFile && FileBrowserHelpers.FileExists(uploadFilePath))
                {
                    FileBrowserHelpers.DeleteFile(uploadFilePath);
                    Debug.Log("Temp File deleted");
                }
            }
        }
    }
Ejemplo n.º 10
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            // If a file was chosen, read its bytes via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
        }
    }
Ejemplo n.º 11
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        /*** TODO: Add file extension filter and request permission ***/
        Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Permission: " + FileBrowser.CheckPermission());
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> File Dialog Opened: " + FileBrowser.Success);
        Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> File Dialog Result: " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Selecting cloth model file");
            try {
                IPAddress  ipAddr        = IPAddress.Parse(clothModelServerIP);
                IPEndPoint localEndPoint = new IPEndPoint(ipAddr, port_no);

                Socket sender = new Socket(ipAddr.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                try {
                    sender.Connect(localEndPoint);
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Socket connected to: " + sender.RemoteEndPoint.ToString());
                    string fileName = FileBrowser.Result;
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Sending file: " + fileName);
                    sender.Send(FileBrowserHelpers.ReadBytesFromFile(fileName));
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> File sent");
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane) {
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> ArgumentNullException: " + ane.ToString());
                }
                catch (SocketException se) {
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> SocketException: " + se.ToString());
                }
                catch (Exception e) {
                    Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Unexpected exception: " + e.ToString());
                }
            }
            catch (Exception e) {
                Debug.Log("UploadClothModel.ShowLoadDialogCoroutine() ===> Other exception: " + e.ToString());
            }
        }
    }
    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Allow multiple selection: true
        // Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(false, true, null, "Load File", "Load"));

        // Dialog is closed
        // Print whether the user has selected some files/folders or cancelled the operation (FileBrowser.Success)
        Debug.Log(FileBrowser.Success);

        if (FileBrowser.Success)
        {
            // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
            for (int i = 0; i < FileBrowser.Result.Length; i++)
            {
                Debug.Log(FileBrowser.Result[i]);
            }

            // Read the bytes of the first file via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

            //------------------ PILS --------------------------------//
            string Vpath = FileBrowser.Result[0];
            string res   = Vpath.Substring(System.Math.Max(0, Vpath.Length - 3));
            print("res:" + res);
            if (res == "mp4" || res == "avi" || res == "mov")
            {
                StaticVariables.VideoPath = Vpath;
                SceneManager.LoadScene(1);
            }
            else
            {
                CanvasGroup cg = GameObject.Find("Canvas").GetComponent <CanvasGroup>();
                cg.alpha          = 1;
                cg.blocksRaycasts = true;
                cg.interactable   = true;
            }

            //------------------------ PILS --------------------------------//
        }
    }
Ejemplo n.º 13
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        // FileBrowser.SetFilters(true, (".png", ".jpg", ".jpeg"));
        // FileBrowser.SingleClickMode = true;
        Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> Permission: " + FileBrowser.CheckPermission());

        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> Success, Result: " + FileBrowser.Success + ", " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> Selecting Pattern");
            string fileName = FileBrowser.Result;
            Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> Saving file: " + fileName);

            path = Path.Combine(Application.persistentDataPath, "Pattern");

            if (Directory.Exists(path))
            {
                /*** TODO extract filename from path ***/
                string[] splitFileName = fileName.Split('/');
                path = Path.Combine(path, splitFileName[splitFileName.Length - 1]);
                Debug.Log("New Path: " + path);
                if (!Directory.Exists(path))
                {
                    File.WriteAllBytes(path, FileBrowserHelpers.ReadBytesFromFile(fileName));
                }
                else
                {
                    Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> File already Uploaded");
                }
            }
            else
            {
                Debug.Log("UploadPatternImage.ShowLoadDialogCoroutine() ===> Directory not found: " + path);
            }
            path = Path.Combine(Application.persistentDataPath, "Pattern");
            p.GenerateList(path);
        }
    }
Ejemplo n.º 14
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load MP3", "Select"));

        path = FileBrowser.Result;

        if (FileBrowser.Success)
        {
            byte[] audioFile = FileBrowserHelpers.ReadBytesFromFile(path);
            musicFileName    = FileBrowserHelpers.GetFilename(path);
            audioSource.clip = NAudioPlayer.FromMp3Data(audioFile);
            fullLength       = (int)audioSource.clip.length;

            canJump          = true;
            audioSource.time = 0;
            AudioProfile(audioProfileVal);
        }

        varUI.GetComponent <UIControl>().enabled           = true;
        varMainCam.GetComponent <ExtendedFlycam>().enabled = true;
    }
Ejemplo n.º 15
0
    // Credits: https://github.com/yasirkula/UnitySimpleFileBrowser
    IEnumerator ShowLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, true, null, "Load File", "Ok"));

        if (FileBrowser.Success)
        {
            for (int i = 0; i < FileBrowser.Result.Length; i++)
            {
                _currentFile = FileBrowser.Result[0];
                Debug.Log(FileBrowser.Result[0]);
            }

            GetExtension(FileBrowser._currentFile, _fileExtension);

            _createGallery.AddButton();
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);
        }

        AddFile2Gallery();
        InsertMediaFile2List(_createGallery._index - 1, FileBrowser._currentFile.Replace(_currenteExtension, string.Empty), _currenteExtension, FileBrowser._sharedPath);
    }
Ejemplo n.º 16
0
    static public IEnumerator ResourceFromArchive()
    {
        FileBrowser.SetFilters(true, new FileBrowser.Filter("ZipArchive", ".zip"));
        FileBrowser.SetDefaultFilter(".zip");
        FileBrowser.SetExcludedExtensions(".exe", ".lnk", ".tmp");

        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
            try
            {
                MemoryStream ms = new MemoryStream(bytes);

                using (ZipArchive zip = new ZipArchive(ms))
                {
                    if (FileBrowserHelpers.GetFilename(FileBrowser.Result) != nameArchive)
                    {
                        ResourceAllocation(zip.GetEntry("DataFile.xml"));
                        nameArchive = FileBrowserHelpers.GetFilename(FileBrowser.Result);
                    }
                    foreach (ZipArchiveEntry entry in zip.Entries)
                    {
                        if (entry.FullName != "DataFile.xml")
                        {
                            ResourceAllocation(entry);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Error: " + e.Message);
                nameArchive = null;
            }
        }
    }
Ejemplo n.º 17
0
        IEnumerator ShowLoadDialogCoroutine()
        {
            // Show a load file dialog and wait for a response from user
            // Load file/folder: both, Allow multiple selection: true
            // Initial path: default (Documents), Initial filename: empty
            // Title: "Load File", Submit button text: "Load"
            yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load"));

            if (FileBrowser.Success)
            {
                // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
                for (int i = 0; i < FileBrowser.Result.Length; i++)
                {
                    _imageSavePath = _songSavePath = FileBrowser.Result[0];
                }

                // Read the bytes of the first file via FileBrowserHelpers
                // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
                byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

                // Or, copy the first file to persistentDataPath
                string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
                FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);

                if (_imageSavePath.ToLower().EndsWith(".png") && _imageSavePath.Length > 1 || _imageSavePath.ToLower().EndsWith(".jpg") && _imageSavePath.Length > 1)
                {
                    string[] world = (Application.platform == RuntimePlatform.Android) ? _imageSavePath.Split('/'): _imageSavePath.Split('\\');
                    _imageName = world[world.Length - 1];
                    GetImage();
                }
                if (_songSavePath.ToLower().EndsWith(".mp3") && _songSavePath.Length > 1)
                {
                    string[] world = (Application.platform == RuntimePlatform.Android) ? _imageSavePath.Split('/') : _imageSavePath.Split('\\');
                    _songName = world[world.Length - 1];
                    GetSong();
                }
            }
        }
Ejemplo n.º 18
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        fundoEscuro.SetActive(true);
        yield return(FileBrowser.WaitForLoadDialog(false, false, null, "Carregar arquivo", "Carregar arquivo"));

        if (FileBrowser.Success)
        {
            pathFile = FileBrowser.Result[0];
            try
            {
                var fileContent = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);
                imagem64 = System.Convert.ToBase64String(fileContent);
                WWW www = new WWW("file:///" + pathFile);
                imagemPreview.texture       = www.texture;
                imagemPreviewGrande.texture = www.texture;
                imagemPreview.gameObject.SetActive(true);
                imagemPreviewGrande.gameObject.SetActive(true);
                foreach (Text texto in textosSemImagem)
                {
                    texto.gameObject.SetActive(false);
                }
                placaSucesso.SetActive(true);
                fundoEscuro.SetActive(false);
            }
            catch (System.Exception ex)
            {
                placaErro.SetActive(true);
                fundoEscuro.SetActive(false);
                Debug.Log(ex);
            }
        }
        else
        {
            placaErro.SetActive(true);
            fundoEscuro.SetActive(false);
        }
    }
Ejemplo n.º 19
0
    public IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Allow multiple selection: true
        // Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(false, true, null, "Load File", "Load"));

        // Dialog is closed
        // Print whether the user has selected some files/folders or cancelled the operation (FileBrowser.Success)
        Debug.Log(FileBrowser.Success);

        if (FileBrowser.Success)
        {
            // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
            for (int i = 0; i < FileBrowser.Result.Length; i++)
            {
                Debug.Log(FileBrowser.Result[i]);
            }

            // Read the bytes of the first file via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);
        }
    }
Ejemplo n.º 20
0
        private IEnumerator ReadBinary(string filename, Action <byte[]> callback = null)
        {
            string url;

            if (Application.platform == RuntimePlatform.Android)
            {
                if (useEmbeddedData)
                {
                    url = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
                    if (url.Contains("://"))
                    {
                        var www = new UnityWebRequest(url);
                        www.downloadHandler = new DownloadHandlerBuffer();
                        yield return(www.SendWebRequest());

                        bytedata = www.downloadHandler.data;
                    }
                    else
                    {
                        bytedata = FileBrowserHelpers.ReadBytesFromFile(url);
                    }
                }
                else
                {
                    url      = filename;
                    bytedata = FileBrowserHelpers.ReadBytesFromFile(url);
                }
                debugString += url + '\n';

//				UIPanel.transform.Find("DebugText").GetComponent<Text>().text = debugString;
            }
            else
            {
                if (useEmbeddedData)
                {
                    url = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
#if UNITY_EDITOR
                    url = "file://" + Application.streamingAssetsPath + '/' + filename;
#endif
                }
                else
                {
                    url = "file://" + filename;
                }
                Debug.Log(url);
                var www = new UnityWebRequest(url);
                www.downloadHandler = new DownloadHandlerBuffer();
                yield return(www.SendWebRequest());

                debugString += url + '\n';

//				UIPanel.transform.Find("DebugText").GetComponent<Text>().text = debugString;

#if UNITY_2020_2_OR_NEWER
                if (www.result == UnityWebRequest.Result.ProtocolError ||
                    www.result == UnityWebRequest.Result.ConnectionError)
#else
                if (www.isHttpError || www.isNetworkError)
#endif
                {
                    Debug.Log(www.error);
                }
                else
                {
                    bytedata = www.downloadHandler.data;
                    if (callback != null)
                    {
                        callback(www.downloadHandler.data);
                    }
                }
            }
        }
Ejemplo n.º 21
0
    /// <summary>
    /// Actually uploads the file to AmazonS3 after getting a presigned request for that file
    /// </summary>
    /// <param name="resp">Response of Presigned Request</param>
    /// <param name="filePath">Path of the file to be uploaded</param>
    /// <param name="isSingleFile">False if it is a part of Folder upload, true otherwise</param>
    /// <param name="ErrorCallback">Used only during Folder upload, callback if any error occurs</param>
    /// <returns></returns>
    IEnumerator UploadFileToAmazonS3(PresignResponse resp, string filePath, bool isSingleFile, Action <bool, string> ErrorCallback)
    {
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();

        byte[] fileData = FileBrowserHelpers.ReadBytesFromFile(filePath);
        string filename = FileBrowserHelpers.GetFilename(filePath);

        formData.Add(new MultipartFormDataSection(nameof(resp.fields.acl), resp.fields.acl));
        formData.Add(new MultipartFormDataSection(nameof(resp.fields.key), resp.fields.key));
        formData.Add(new MultipartFormDataSection("x-amz-algorithm", resp.fields.xamzalgorithm));
        formData.Add(new MultipartFormDataSection("x-amz-credential", resp.fields.xamzcredential));
        formData.Add(new MultipartFormDataSection("x-amz-date", resp.fields.xamzdate));
        formData.Add(new MultipartFormDataSection(nameof(resp.fields.policy), resp.fields.policy));
        formData.Add(new MultipartFormDataSection("x-amz-signature", resp.fields.xamzsignature));
        formData.Add(new MultipartFormFileSection("file", fileData, filename, "application/octet-stream"));
        using (UnityWebRequest uwr = UnityWebRequest.Post(resp.url, formData))
        {
            if (isSingleFile)
            {
                uwr.SendWebRequest();

                MessageFields uploadMsgFields = DisplayUploadProgressMessage();
                StartCoroutine(CheckUploadConnection(uwr));
                while (!uwr.isDone)
                {
                    string progress = "Progress : " + Mathf.Round(uwr.uploadProgress * 100).ToString() + "%";
                    uploadMsgFields.MessageDetails("Upload Progress ...", progress);
                    if (uwr.isNetworkError || uwr.isHttpError)
                    {
                        DestroyUploadProgressMessage(uploadMsgFields);
                        yield break;
                    }
                    yield return(null);
                }
                DestroyUploadProgressMessage(uploadMsgFields);
            }
            else
            {
                yield return(uwr.SendWebRequest());
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                if (isSingleFile)
                {
                    DisplayUploadErrorMessage(uwr.error);
                }
                else
                {
                    ErrorCallback(true, uwr.error + "\n" + resp.fields.key);
                }
            }
            else
            {
                Debug.Log("File Upload Success! : " + filename);
                //Debug.Log(uwr.GetResponseHeader("Location"));
                if (filename.EndsWith(TypeGLTF) || filename.EndsWith(TypeGLB))
                {
                    gltfUrl = uwr.GetResponseHeader("Location");
                    gltfUrl = UnityWebRequest.UnEscapeURL(gltfUrl);
                    if (isSingleFile)
                    {
                        yield return(PushUrlToDatabase(gltfUrl));
                    }
                }
            }
        }
    }