简体   繁体   中英

How to upload Base64 image into firebase using .NET Core

In my application, Image is coming as a Base64 string and I need to store it in Firebase Storage. To achieve that what I did was, first decode Base64 into the image and then storing it into the local server. After that uploading to FirebaseStorage from the server path. Once after the uploading to the Firebase, deleting the image from the local server. My sample code as follows,

string filename = "stackoverflow.jpg";
var folderPath = Path.Combine(_hostingEnv.WebRootPath, "dev");

//Creating dev foder if not exists
if (!Directory.Exists(folderPath)) {
  Directory.CreateDirectory(folderPath);
}

var path = Path.Combine(folderPath, filename);
File.WriteAllBytes(path, Convert.FromBase64String(req.Data));
var firebaseAutProvider = new FirebaseAuthProvider(new FirebaseConfig(_configuration["FirebaseConfig:ApiKey"]));
var firebaseAuthLink = await firebaseAutProvider.SignInWithEmailAndPasswordAsync(_configuration["FirebaseConfig:AuthEmail"], _configuration["FirebaseConfig:AuthPassword"]);

//  CancellationTokenSource can be used to cancel the upload midway
var cancellation = new CancellationTokenSource();

using(FileStream fileStream = new FileStream(path, FileMode.Open)) {
  var task = new FirebaseStorage(
      _configuration["FirebaseConfig:Bucket"],
      new FirebaseStorageOptions {
        AuthTokenAsyncFactory = () => Task.FromResult(firebaseAuthLink.FirebaseToken),
          ThrowOnCancel = true // when cancel the upload, exception is thrown. By default no exception is thrown
      })
    .Child("dev") //uploading to the firebase's storage dev folder
    .Child(_configuration["FirebaseConfig:ImageFolder"])
    .PutAsync(fileStream, cancellation.Token);
  //task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");
  imageAccessLink = await task;
  fileStream.Dispose();
}

//Delete uploaded file from the local server, after uploading to the firebase
if (File.Exists(path))
  File.Delete(path);

It's working fine, but my concern is, I need to this without using Local server, which means, I need to direct upload Base64 into the firebase without saving it to the local server. How can I do it? I searched and found Upload a base64 image with Firebase Storage . But problem is doing this through the.Net. Thanks in advance.

You only need to use the Base64String to create the stream to send to Firebase, (normally it only have to be aa stream, not specifically a filestream) something like:

byte[] bytes = Convert.FromBase64String(imageInbase64);

using(MemoryStream fileStream = new MemoryStream(bytes)) {
  var task = new FirebaseStorage(
      _configuration["FirebaseConfig:Bucket"], 
      //Continue your code ....

If it REALLY need to be a file stream, copy the stream internally before sending Use

 tmpStream.WriteTo(fileStream);

or

 tmpStream.Position = 0;
 tmpStream.CopyTo(fileStream);

Instead of writing your byte array to a path and creating FileStream to write to firebase, you can create a MemoryStream from the same byte array ( Convert.FromBase64String(req.Data) ) like so:

MemoryStream stream = new MemoryStream(Convert.FromBase64String(req.Data));

and then pass that stream instead of filestream to PutAsync

.PutAsync(stream, cancellation.Token);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM