簡體   English   中英

通過 HTTP 上傳圖片到 firebase 存儲

[英]Upload image to firebase storage via HTTP Post

我想將圖像上傳到 flutter web 應用程序中的 firebase 存儲中。 到目前為止我所做的:

  • 通過雲功能接收簽名URL; 如此處所述谷歌指南:創建簽名的 URL - 在文章的底部
  • 通過 flutter package "image_picker_web" Package-Link從本地文件加載圖像
  • 選擇器提供 (Image-)Widget、Uint8List、html.File
  • 嘗試通過 MultipartRequest 將圖像上傳到 signedURL,但收到錯誤: XMLHttpRequest error ,但沒有任何進一步的詳細信息。

我的 MultipartRequest 代碼(Uint8List 類型的字節):

var multipartFile = http.MultipartFile.fromBytes(
  'image', bytes, filename: 'test.jpeg', // optional
  contentType: new MediaType('image', 'jpeg'),
);
var uri = Uri.parse(url);
var request = http.MultipartRequest("POST", uri)
  ..files.add(multipartFile);
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');
response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });

...我也嘗試過 stream:

var stream = http.ByteStream.fromBytes(bytes);
var multipartFile = new http.MultipartFile('file', stream, bytes.length,
      filename: 'test.jpeg', contentType: new MediaType('image', 'jpeg'));

我認為圖像數據/類型(MultipartFile)有問題或 url 不起作用或完整的 MultipartRequest 不符合 firebase 存儲

是否有人對此有解決方案,或者我該如何進一步調查該問題?

如果您檢查瀏覽器控制台,您很可能會收到 CORS 錯誤。

有一種更好的方法可以將圖像上傳到 Firebase,這是上傳圖像的代碼,並接收存儲圖像的 URL。

import 'dart:async';
import 'package:firebase/firebase.dart' as fb;
import 'dart:html' as html;

String url;

Future<String> uploadProfilePhoto(html.File image, {String imageName}) async {
  try {
    //Upload Profile Photo
    fb.StorageReference _storage = fb.storage().ref('displayPhotos/$imageName');
    fb.UploadTaskSnapshot uploadTaskSnapshot = await _storage.put(image).future;
    // Wait until the file is uploaded then store the download url
    var imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
    url = imageUri.toString();
  } catch (e) {
    print(e);
  }
  return url;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM