如何使用 .NET Core 将 Base64 图像上传到 firebase

How to upload Base64 image into firebase using .NET Core

在我的应用程序中,图像以 Base64 字符串的形式出现,我需要将其存储在 Firebase 存储中。为此,我所做的是,首先将 Base64 解码为图像,然后将其存储到本地服务器。之后从服务器路径上传到 FirebaseStorage。上传到 Firebase 后,从本地服务器删除图像。我的示例代码如下,

string filename = "Whosebug.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);

它工作正常,但我担心的是,我需要在不使用本地服务器的情况下执行此操作,这意味着我需要直接将 Base64 上传到 firebase 中而不将其保存到本地服务器。我该怎么做?我搜索并找到 Upload a base64 image with Firebase Storage。但问题是通过 .Net 这样做。提前致谢。

您只需要使用 Base64String 创建要发送到 Firebase 的流,(通常它只需要是一个流,而不是特定的文件流),例如:

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

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

如果确实需要文件流,请在发送前在内部复制流 使用

 tmpStream.WriteTo(fileStream);

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

无需将字节数组写入路径并创建 FileStream 以写入 firebase,您可以从相同的字节数组 (Convert.FromBase64String(req.Data)) 创建 MemoryStream,如下所示:

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

然后将该流而不是文件流传递给 PutAsync

.PutAsync(stream, cancellation.Token);