尝试从 Firebase 存储上传/打开文件

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

React Native 应用程序。我正在做的是上传一个文件,无论是图片还是pdf。我的问题是我似乎无法打开上传的文件。 “文件正在上传到存储”。

export const uploadToStorage = async (document: any) => {
  try {
    const storage = getStorage();
    const fileName = document?.name;

    const storageRef = ref(storage, `files/${fileName}`);
    
    const fileRef = ref(storageRef);
    const fileType = document?.mimeType;
    const metaData = {
      contentType: fileType
    };
    const snapshot = await uploadBytesResumable(storageRef, document, metaData);
    console.log('Upload successful:', snapshot);

    const downloadURL = await getDownloadURL(fileRef);
    console.log('Download URL:', downloadURL);
    return downloadURL;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}
 const _pickDocument = async () => {
    const result = await DocumentPicker.getDocumentAsync({
      multiple: false,
    })
    if (result !== null) {
      result.assets?.map(async (item: any) => {
        const filePrefix = 'file://'
        if (item.uri.startsWith(filePrefix)) {
          item.uri = item.uri.substring(filePrefix.length)
        }
        console.log('URL:' + item.mimeType)
        dispatch(addPDF(item.name))
        if (auth.currentUser?.uid !== null) {
          console.log(auth.currentUser?.uid)
          
          await uploadToStorage(item).then((downloadUrl) => {
            setDownloadUrl(downloadUrl)
            
          }) 
        }
      })
    }
  }
service firebase.storage {
  match /b/{bucket}/o {
    // Allow read and write access to all files
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

我尝试发送不同的标头/元数据,但它没有做出改变。我尝试了 uploadBytes 而不是 uploadBytesResumable 和同样的事情。

文件已正确上传,但我无法从 firbase 存储手动打开它。

如果我上传 pdf,我会收到错误:无法加载 PDF 文档。

typescript firebase react-native file-upload firebase-storage
1个回答
0
投票

根据其文档,

uploadBytesResumable
采用
Blob | Uint8Array | ArrayBuffer
作为其数据。据我所知,您的
item
/
document
DocumentPickerAsset
,这不是可接受的类型。

您需要从资产中的 File

读取字节
,并将 那些传递到 Firebase。

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