簡體   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