step-up-labs / firebase-storage-dotnet

C# library for Firebase Storage
MIT License
140 stars 35 forks source link

Fails to upload files from the local folder #3

Closed ghost closed 7 years ago

ghost commented 7 years ago

I am having trouble uploading files(.mp3) stored in the local folder by user to firebase. This is how a file is retrieved from local folder:

StorageFolder folder = ApplicationData.Current.LocalFolder;

var songfolder = await folder.GetFolderAsync("Songs");

StorageFile mp3file = await songfolder.GetFileAsync(mp3fileforupload); 

And this is how I create a stream file of the file and upload:

var stream = File.Open(mp3file.Path, FileMode.Open);

var task = new FirebaseStorage("-my-bucket-.appspot.com")
                       .Child("songs")
                       .Child(new_song_id)
                       .PutAsync(stream);

task.Progress.ProgressChanged += (s, f) => uploadProgress(f.Percentage);

var downloadurl = await task;
Debug.WriteLine("DOWNLOAD_URL " + downloadurl);

The file fails to upload. I understand that files should be uploaded as a stream of a file. This worked when uploading files from the Assets folder, but does not work with files from local folder. I have tried uploading from the MostRecentlyUsedList but it still fails to upload. Any idea why this is failing?

bezysoftware commented 7 years ago

I don't think you can use the File API in UWP app. Once you get the StorageFile you should do:

var randomStream = await mp3File.OpenAsync(Windows.Storage.FileAccessMode.Read);
var stream = randomStream.AsStream();
... 
ghost commented 7 years ago

I initially tried this:

var randomStream = await mp3File.OpenAsync(Windows.Storage.FileAccessMode.Read);
var stream = randomStream.AsStream();
...

But it failed to upload the file.

What has worked for me is using a MemoryStream.

First I retrieved the file from local folder:

StorageFolder folder = ApplicationData.Current.LocalFolder;

var songfolder = await folder.GetFolderAsync("Songs");

StorageFile mp3file = await songfolder.GetFileAsync(mp3fileforupload);

Then I read the bytes of the file using a DataReader:

 byte[] fileBytes = null;
 using (IRandomAccessStreamWithContentType stream = await mp3file.OpenReadAsync())
 {
   fileBytes = new byte[stream.Size];
   using (DataReader reader = new DataReader(stream))
     {
       await reader.LoadAsync((uint)stream.Size);
       reader.ReadBytes(fileBytes);
     }
 }

Then I used a MemoryStream for the upload:

Stream stream = new MemoryStream(fileBytes);

var task = new FirebaseStorage("-my-bucket-.appspot.com")
           .Child("songs")
           .Child(new_song_id)
           .PutAsync(stream);

task.Progress.ProgressChanged += (s, f) => uploadProgress(f.Percentage);

var downloadurl = await task;

That did the trick. The file uploaded.