protected IEnumerator UploadToFirebaseStorage() { StorageReference reference = FirebaseStorage.DefaultInstance .GetReferenceFromUrl(firebaseStorageLocation); #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 var task = reference.PutBytesAsync(Encoding.UTF8.GetBytes(fileContents), null, null, default(System.Threading.CancellationToken), null); #else var task = reference.PutBytesAsync(Encoding.UTF8.GetBytes(fileContents)); #endif yield return(new WaitUntil(() => task.IsCompleted)); if (task.IsFaulted) { DebugLog(task.Exception.ToString()); throw task.Exception; } else { fileContents = ""; DebugLog("Finished uploading... Download Url: " + task.Result.DownloadUrl.ToString()); DebugLog("Press the Download button to download text from Cloud Storage"); } }
/* * public void OnTokenReceived(object Sender, Firebase.Messaging.TokenReceivedEventArgs EventArgs) * { * Debug.Log("Firebase Messaging - Token de Registro Recebido: " + EventArgs.Token); * } * * public void OnMessageReceived(object Sender, Firebase.Messaging.MessageReceivedEventArgs EventArgs) * { * Debug.Log("Firebase Messaging - Recebida uma nova mensagem de: " + EventArgs.Message.From); * } */ public static void UploadByte(byte[] File, string Path, string Type, string Database) { StorageReference FileReference = StorageReference.Child(Path); var Metadata = new MetadataChange(); Metadata.ContentType = "image/" + Type.Replace(".", ""); FileReference.PutBytesAsync(File, Metadata).ContinueWith(Task => { if (Task.IsFaulted || Task.IsCanceled) { Debug.Log(Task.Exception.ToString()); TecWolf.System.SystemInterface.Alert("Arquivo não enviada com sucesso, tente novamente."); } else { TecWolf.System.SystemInterface.Alert("Arquivo enviado com sucesso."); FileReference.GetDownloadUrlAsync().ContinueWith(TaskDownload => { if (TaskDownload.IsCompleted) { Debug.Log("Download URL: " + TaskDownload.Result); DownloadUrl = TaskDownload.Result.ToString(); FirebaseController.WriteDataString(Database, "link", FirebaseController.DownloadUrl); } }); } }); }
private void SendAudio(string key, float[] audio) { //Using the Buffer solution audio_ref = storage_ref.Child(key); byte[] byteSamples = new byte[audioClipFromDB.samples * 4]; System.Buffer.BlockCopy(audio, 0, byteSamples, 0, byteSamples.Length); audio_ref.PutBytesAsync(byteSamples) .ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { //audioSource.Play(); Debug.Log("Uploading Failed"); Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { Debug.Log("Upload Success"); Firebase.Storage.StorageMetadata metadata = task.Result; string download_url = metadata.Reference.GetDownloadUrlAsync().ToString(); } }); }
public void UploadFile(string childpathString, byte[] _data) { FirebaseStorage storage = FirebaseStorage.DefaultInstance; StorageReference storageRef = storage.RootReference; // Create a reference to the file you want to upload StorageReference childRef = storageRef.Child(childpathString);// ("profileImages/"+auth.CurrentUser.UserId+".jpg"); // Upload the file to the path "images/rivers.jpg" childRef.PutBytesAsync(_data) .ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and download URL. StorageMetadata metadata = task.Result; string md5Hash = metadata.Md5Hash; Debug.Log("Finished uploading..."); Debug.Log("md5 hash = " + md5Hash); //Debug.Log("md5 hash = " + "gs://konnekt4march.appspot.com"+profileImagesRef.Path); _uploadcomplete?.Invoke(childRef.Path); } }); }
public IEnumerator UploadToFirebaseStorage(string path, byte[] bs, Action <StorageMetadata> doneCB, Action <Exception> ecb) { string firebaseStorageLocation = MyStorageBucket + path; StorageReference reference = FirebaseStorage.DefaultInstance .GetReferenceFromUrl(firebaseStorageLocation); var task = reference.PutBytesAsync(bs); yield return(new WaitUntil(() => task.IsCompleted)); if (task.IsFaulted) { if (ecb != null) { ecb(task.Exception); } else { throw task.Exception; } } else { doneCB(task.Result); } }
public void testFirebase(string key) { //Using the Buffer solution audio_ref = storage_ref.Child(key); uploading.text = "Uploading"; float[] samples = new float[audioClipFromDB.samples]; audioClipFromDB.GetData(samples, 0); byte[] byteSamples = new byte[audioClipFromDB.samples * 4]; System.Buffer.BlockCopy(samples, 0, byteSamples, 0, byteSamples.Length); audio_ref.PutBytesAsync(byteSamples) .ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { //audioSource.Play(); Debug.Log("Uploading Failed"); Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and download URL. Debug.Log("Upload Success"); //audioSource.Play(); Firebase.Storage.StorageMetadata metadata = task.Result; //audioSource.Play(); string download_url = metadata.Reference.GetDownloadUrlAsync().ToString(); Debug.Log("Finished uploading..."); Debug.Log("download url = " + download_url); uploading.text = "Upload"; } }); //audioSource.Play(); }
/// <summary> /// upload the Live2D model to server /// </summary> /// <param name="filepath">Current live2D model.json file</param> public async Task UploadLive2D(string filepath) { var fileType = new MetadataChange(); //setup compressor ModelCompressor comp = new ModelCompressor(); string data = null; await Task.Run(() => { data = comp.CompressAsync(filepath).Result; }); StorageReference moc3Path = Storage_ref.Child("VRP/" + CurrentUser.UserId + "/Live2D/" + Path.GetFileNameWithoutExtension(filepath) + "_model.json"); isUploading = true; fileType.ContentType = "application/json"; await moc3Path.PutBytesAsync(System.Text.Encoding.UTF8.GetBytes(data), fileType).ContinueWith((Task <StorageMetadata> task) => { Debug.Log("start uploading"); if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! isUploading = false; } else { metadata = task.Result; Debug.Log("Finished uploading..."); } isUploading = false; }); }
IEnumerator UploadToFirebaseStorage() { Loading.SetActive(true); firebaseStorageLocation = MyStorageBucket + fileContents.Substring(fileContents.LastIndexOf('/') + 1); StorageReference reference = FirebaseStorage.DefaultInstance .GetReferenceFromUrl(firebaseStorageLocation); if (string.IsNullOrEmpty(fileContents)) { AddChildUser(); } else { byte[] byteArray = File.ReadAllBytes(fileContents); var task = reference.PutBytesAsync(byteArray); yield return(new WaitUntil(() => task.IsCompleted)); if (task.IsFaulted) { Debug.Log(task.Exception.ToString()); Loading.SetActive(false); } else { imageURL = task.Result.DownloadUrl.ToString(); AddChildUser(); Debug.Log("Finished uploading... Download Url: " + task.Result.DownloadUrl.ToString()); Debug.Log("Press the Download button to download text from Cloud Storage"); } } }
public void upload(byte[] custom_bytes, string fbPath, Action <string> cb) { authDoneCB.add(() => { StorageReference rivers_ref = getByPath(fbPath); // Upload the file to the path "images/rivers.jpg" rivers_ref.PutBytesAsync(custom_bytes) .ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and download URL. Firebase.Storage.StorageMetadata metadata = task.Result; string download_url = metadata.Path; UnityMainThreadDispatcher.uniRxRun(() => { cb(metadata.Path); Debug.Log("Finished uploading..."); }); } }); }); }
/// <summary> /// upload VRM file to server /// </summary> /// <param name="filepath">Current VRM model path</param> public async Task UploadVRM(string filepath) { var fileType = new MetadataChange(); StorageReference vrmPath = Storage_ref.Child("VRP/" + CurrentUser.UserId + "/vrm/" + Path.GetFileName(filepath)); //get thumbnail form vrm var context = new VRMImporterContext(); byte[] vrmByte = null; using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { vrmByte = new byte[fs.Length]; fs.Read(vrmByte, 0, vrmByte.Length); context.ParseGlb(vrmByte); } var meta = context.ReadMeta(true); string th; byte[] thumbnailData = meta.Thumbnail.EncodeToPNG(); try { th = Convert.ToBase64String(thumbnailData); } catch (Exception e) { th = ""; } isUploading = true; fileType.ContentType = "application/vrm"; await vrmPath.PutBytesAsync(vrmByte, fileType).ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! isUploading = false; } else { // Metadata contains file metadata such as size, content-type, and download URL. metadata = task.Result; Debug.Log("Finished uploading..."); } isUploading = false; }); }
public static void Save(bool uploadToCloud = false) { string json = JsonUtility.ToJson(Progress); PlayerPrefs.SetString(PROGRESS_KEY, json); if (uploadToCloud) { AnalyticsManager.SetUserProperties("gold", Progress.Gold.ToString()); byte[] data = Encoding.Default.GetBytes(json); StorageReference targetStorage = GetTargetCloudStorage(); targetStorage.PutBytesAsync(data); } }
public void UploadFile(string fileName, byte[] data) { StorageReference fileRef = storage.RootReference.Child(fileName); fileRef.PutBytesAsync(data).ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); } else { Debug.Log("Finished uploading: " + fileName); uploaded = true; } }); }
IEnumerator uploadFile(StorageReference fileRef, byte[] data) { // File located on disk //string local_file = "E://green.png"; var task = fileRef.PutBytesAsync(data); yield return(new WaitUntil(() => task.IsCompleted)); if (task.IsFaulted) { Debug.Log(task.Exception.ToString()); throw task.Exception; } else { Debug.Log("Finished uploading... Download Url: " + task.Result.DownloadUrl.ToString()); Debug.Log("Press the Download button to download text from Cloud Storage"); } }
IEnumerator UploadToFirebaseStorage() { StorageReference reference = FirebaseStorage.DefaultInstance .GetReferenceFromUrl(firebaseStorageLocation); var task = reference.PutBytesAsync(Encoding.UTF8.GetBytes(fileContents)); yield return(new WaitUntil(() => task.IsCompleted)); if (task.IsFaulted) { DebugLog(task.Exception.ToString()); } else { fileContents = ""; DebugLog("Finished uploading... Download Url: " + task.Result.DownloadUrl.ToString()); DebugLog("Press the Download button to download text from Firebase Storage"); } }
public static void UploadBytes(byte[] bytes, string saveName, string saveAt) { StorageReference postTextRef = storage.RootReference.Child(saveAt + "/" + saveName); postTextRef.PutBytesAsync(bytes).ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and md5hash. StorageMetadata metadata = task.Result; string md5Hash = metadata.Md5Hash; Debug.Log("Finished uploading..."); Debug.Log("md5 hash = " + md5Hash); } }); }
private void CreatePlayerRecordFile() { string fileName = this.GenerateRecordFileName(); while (File.Exists(fileName)) { this.round++; fileName = this.GenerateRecordFileName(); } string json = JsonUtility.ToJson(this); Directory.CreateDirectory(@"Records/" + this.bossName); System.IO.File.WriteAllText(fileName, json); FirebaseApp app = FirebaseApp.Create(); FirebaseStorage storage = FirebaseStorage.GetInstance(CLOUD_STORAGE_URL); this.storage_ref = storage.GetReferenceFromUrl(CLOUD_STORAGE_URL); StorageReference record_ref = this.storage_ref.Child(fileName); record_ref.PutBytesAsync(Encoding.UTF8.GetBytes(json)) .ContinueWith(task => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and download URL. Firebase.Storage.StorageMetadata metadata = task.Result; string download_url = metadata.DownloadUrl.ToString(); Debug.Log("Finished uploading..."); Debug.Log("download url = " + download_url); this.isFileUploaded = true; } }); alertText.gameObject.SetActive(true); }
public static void UserUploadToFirebase(LevelManager.Level level) { DatabaseReference data = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl("https://blockquest-a1e16.firebaseio.com/"); StorageReference levelFolder = root.Child(saveLoc); StorageReference userName = levelFolder.Child(FormattedUserName); StorageReference userLevel = userName.Child(level.LevelName); StorageReference levelFile = userLevel.Child(level.LevelName + ".xml"); StorageReference levelPic = userLevel.Child(level.LevelName + ".png"); levelFile.PutFileAsync(level.LevelPath); levelPic.PutBytesAsync(level.LevelPic.EncodeToPNG()); Level newLevel = new Level(level.LevelName, levelFile.Path, levelPic.Path); Debug.Log(levelFile.Path); Debug.Log(levelPic.Path); data.Child(saveLoc).Child(FirebaseManager.FormattedUserName).Child(level.LevelName).Child("File_Path").SetValueAsync(newLevel.filePath); data.Child(saveLoc).Child(FirebaseManager.FormattedUserName).Child(level.LevelName).Child("Picture_Path").SetValueAsync(newLevel.picturePath); }
public static void UploadFileToFirebase(LevelManager.Level level) { DatabaseReference data = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl("https://blockquest-a1e16.firebaseio.com/"); StorageReference levelFolder = root.Child(saveLoc); StorageReference userLevel = levelFolder.Child(level.LevelName); StorageReference levelFile = userLevel.Child(level.LevelName + ".xml"); StorageReference levelPic = userLevel.Child(level.LevelName + ".png"); levelFile.PutFileAsync(level.LevelPath); levelPic.PutBytesAsync(level.LevelPic.EncodeToPNG()); Level newLevel = new Level(level.LevelName, levelFile.Path, levelPic.Path); data.Child(saveLoc).Child(level.LevelName).Child("File_Path").SetValueAsync(newLevel.filePath); data.Child(saveLoc).Child(level.LevelName).Child("Picture_Path").SetValueAsync(newLevel.picturePath); if (saveLoc == "Default_Levels") { data.Child("Base_Level_Last_Changed").SetValueAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); } }
public void Post() { clone = UIHelper.PushAndGetPrefabToParent(post, content.transform, 0); PostElement pe = clone.GetComponent <PostElement>(); pe.postText = postText.text; // Upload Text FirebaseStorage storage = FirebaseStorage.DefaultInstance; StorageReference postTextRef = storage.RootReference.Child("posts/" + "username" + "/" + "nextID" + "/" + "postText"); byte[] postTextbytes = Encoding.ASCII.GetBytes(pe.postText); postTextRef.PutBytesAsync(postTextbytes).ContinueWith((Task <StorageMetadata> task) => { if (task.IsFaulted || task.IsCanceled) { Debug.Log(task.Exception.ToString()); // Uh-oh, an error occurred! } else { // Metadata contains file metadata such as size, content-type, and md5hash. StorageMetadata metadata = task.Result; string md5Hash = metadata.Md5Hash; Debug.Log("Finished uploading..."); Debug.Log("md5 hash = " + md5Hash); } }); if (imgBoard.transform.childCount > 0) //there're images { foreach (Transform child in imgBoard.transform) { pe.ImageQueue.Add(child.gameObject.GetComponent <Image>()); } } StartCoroutine(SiblingUpdate()); pe.updateAll(); }
private IEnumerator UploadCoroutine(Texture2D screenshot) { #region DateTime-Set DateTime dateTime = DateTime.Now; // 시-분-초 string time = dateTime.Hour.ToString() + "-" + dateTime.Minute.ToString() + "-" + dateTime.Second.ToString(); #endregion string TOTAL_DATE = dateTime.ToShortDateString() + "+" + time; FirebaseStorage storage = FirebaseStorage.DefaultInstance; StorageReference screenshotReference = storage.GetReferenceFromUrl(PATH).Child($"/screenshots/{TOTAL_DATE}.png"); #region Set-Metadata var metadataChange = new MetadataChange() { ContentEncoding = "image/png", /* 여기는 메타데이터 설정 * CustomMetadata = new Dictionary<string, string>() * { * { "Position", Camera.main.transform.position.ToString()}, * { "Rotation", Camera.main.transform.position.ToString()} * } */ }; #endregion var bytes = screenshot.EncodeToPNG(); var uploadTask = screenshotReference.PutBytesAsync(bytes, metadataChange); yield return(new WaitUntil(() => uploadTask.IsCompleted)); if (uploadTask.Exception != null) { Debug.LogError($"업로드에 실패했습니다. {uploadTask.Exception}"); yield break; } }
// Returns the top times, given the level's database path and map id. // Upload the replay data to Firebase Storage private static Task <StorageMetadata> UploadReplayData( UserScore userScore, ReplayData replay, UploadConfig config) { StorageReference storageRef = FirebaseStorage.DefaultInstance.GetReference(config.storagePath); // Serializing replay data to byte array System.IO.MemoryStream stream = new System.IO.MemoryStream(); replay.Serialize(stream); stream.Position = 0; byte[] serializedData = stream.ToArray(); // Add database path and time to metadata for future usage MetadataChange newMetadata = new MetadataChange { CustomMetadata = new Dictionary <string, string> { { "DatabaseReplayPath", config.dbSharedReplayPath }, { "DatabaseRankPath", config.dbRankPath }, { "Time", userScore.Score.ToString() }, { "Shared", config.shareReplay.ToString() }, } }; return(storageRef.PutBytesAsync(serializedData, newMetadata)); }