繁体   English   中英

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

[英]How to upload Base64 image into firebase using .NET Core

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

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);

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

您只需要使用 Base64String 来创建 stream 以发送到 Firebase,(通常它只需要是 aa stream,而不是特定的文件流):

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

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

如果它真的需要是一个文件 stream,在发送之前复制 stream 内部使用

 tmpStream.WriteTo(fileStream);

或者

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

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

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

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

.PutAsync(stream, cancellation.Token);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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