如何将图像上传到Firebase存储器

问题描述 投票:0回答:1

此代码中我缺少什么?它不允许我的图像正确上传。我已使用firebase指南将个人资料图片上传到firebase存储,但是当图片上传时,此错误会在文件夹中弹出

由于文件“ ProfileImage.jpg”为空,因此无法打开。大小0字节

    let storage = Storage.storage()
        let storageRef = storage.reference()
        let data = Data()
         let starsRef = storageRef.child("ProfileImage.jpg")
        let metadata = StorageMetadata()
        metadata.contentType = "ProfileImage/jpeg"
        let uploadTask = starsRef.putData(data, metadata: nil) { (metadata, error) in
         guard let metadata = metadata else {
           return
         }

         let size = metadata.size

         starsRef.downloadURL { (url, error) in
           guard let downloadURL = url else {

             return
           }
         }
       }
ios firebase url metadata firebase-storage
1个回答
0
投票

尝试使用以下代码

// File or Blob named mountains.jpg
var file = ...

// Create the file metadata
var metadata = {
   contentType: 'image/jpeg'
};

// Upload file and metadata to the object 'images/mountains.jpg'
var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);

// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function(snapshot) {
    // Get task progress, including the number of bytes uploaded and the total number 
       of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
  case firebase.storage.TaskState.PAUSED: // or 'paused'
    console.log('Upload is paused');
    break;
  case firebase.storage.TaskState.RUNNING: // or 'running'
    console.log('Upload is running');
    break;
 }
}, function(error) {

   // A full list of error codes is available at
   // https://firebase.google.com/docs/storage/web/handle-errors
 switch (error.code) {
    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;

    case 'storage/canceled':
      // User canceled the upload
      break;

    ...

   case 'storage/unknown':
      // Unknown error occurred, inspect error.serverResponse
      break;
  }
 }, function() {
     // Upload completed successfully, now we can get the download URL
     uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
        console.log('File available at', downloadURL);
  });
 });

To get all Errors Handle Messages Click Here

© www.soinside.com 2019 - 2024. All rights reserved.