用于 Firebase 存储的 Pdf 到 Blob

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

我正在尝试将 PDF 转换为 Blob,以便可以将其上传到 Firebase 存储。虽然我可以在 Firebase 控制台中看到上传的 PDF,但无法打开它。我收到错误:“无法加载 PDF 文件。”

这是转换函数:

const uriToBlob = async (uri) => {
    try {
      const response = await fetch(uri);
      if (!response.ok) {
        throw new Error('Failed to fetch resource');
      }
      const blob = await response.blob();
      return blob;
    } catch (error) {
      throw error;
    }
  };

我这样执行转换:

const userCredentials = getCredentials();
        if (!userCredentials) {
            console.error('User credentials not found');
            return;
        }

        try {
            // Convert file URI to Blob
            fileBlob = await uriToBlob(fileUri);
            console.log('Blob size:', fileBlob);
            // Upload file to Firebase Storage
            const storage = getStorage();
            const storageRef = ref(storage, 'notes/' + filename);

            // Get download URL of the uploaded file
            const metadata = {
                contentType: 'application/pdf'
            };
            const snapshot = await uploadBytes(storageRef, fileBlob, metadata);
            const fileUrl = await getDownloadURL(storageRef);
javascript firebase google-cloud-firestore blob
1个回答
0
投票

试试这个:

const uriToBlob = async (uri) => {
    try {
        const response = await fetch(uri);
        if (!response.ok) {
            throw new Error('Failed to fetch resource, status: ' + response.status);
        }
        console.log('Content-Type:', response.headers.get('Content-Type'));
        const blob = await response.blob();
        console.log('Blob type:', blob.type);
        console.log('Blob size:', blob.size);
        return blob;
    } catch (error) {
        throw error;
    }
};

还有这个:

const userCredentials = getCredentials();
if (!userCredentials) {
    console.error('User credentials not found');
    return;
}

try {
    const fileBlob = await uriToBlob(fileUri);
    console.log('Blob size:', fileBlob.size);

    const storage = getStorage();
    const storageRef = ref(storage, 'notes/' + filename);

    const metadata = {
        contentType: 'application/pdf'
    };

    const snapshot = await uploadBytes(storageRef, fileBlob, metadata);

    const fileUrl = await getDownloadURL(storageRef);
    console.log('File URL:', fileUrl);
} catch (error) {
    console.error('Error uploading file:', error);
}

并检查控制台中的所有值,确保所有值均正确且

Blob type
application/pdf

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