1

firebase-adminとfirebase-functionsを使用してFirebase Storageにファイルをアップロードします。firebase-adminでアップロードされたファイルからパブリックURLを取得

service firebase.storage { 
    match /b/{bucket}/o { 
    match /images { 
     allow read; 
     allow write: if false; 
    } 
    } 
} 

そして、私はこのコードでパブリックURLを取得したい:

私はストレージにこのルールを持っている

const config = functions.config().firebase; 
const firebase = admin.initializeApp(config); 
const bucketRef = firebase.storage(); 

server.post('/upload', async (req, res) => { 

    // UPLOAD FILE 

    await stream.on('finish', async() => { 
     const fileUrl = bucketRef 
      .child(`images/${fileName}`) 
      .getDownloadUrl() 
      .getResult(); 
     return res.status(200).send(fileUrl); 
     }); 
}); 

をしかし、私はこのエラー.child is not a functionを持っています。 firebase-adminでファイルのパブリックURLを取得するにはどうすればよいですか? using Cloud Storage documentation上のサンプルアプリケーションコードから

答えて

2

、アップロードが成功した後、公共のダウンロードURLを取得するには、次のコードを実装することができるはずです。また

// Create a new blob in the bucket and upload the file data. 
const blob = bucket.file(req.file.originalname); 
const blobStream = blob.createWriteStream(); 

blobStream.on('finish',() => { 
    // The public URL can be used to directly access the file via HTTP. 
    const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`); 
    res.status(200).send(publicUrl); 
}); 

、あなたが公にアクセス、ダウンロードが必要な場合

をあなたはを使用して署名したURLを生成する必要があります:管理者SDKはこれを直接サポートしていないため、URLは、クラウドストレージNPMモジュールからgetSignedUrl()を使用することを提案this answerを参照してくださいNPMモジュール @google-cloud/storageを介して3210。

例:

const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'}); 
// ... 
const bucket = gcs.bucket(bucket); 
const file = bucket.file(fileName); 
return file.getSignedUrl({ 
    action: 'read', 
    expires: '03-09-2491' 
}).then(signedUrls => { 
    // signedUrls[0] contains the file's public URL 
}); 
+0

はい@Grimthorrが、匿名ユーザーがファイルにアクセスすることはできません。 – SaroVin

+1

申し訳ありませんが、代わりにパブリックアクセスのダウンロードURLを入手したいですか? Firefoxのクラウド機能でアップロードされたファイルからダウンロードURLを取得してください(https://stackoverflow.com/q/42956250/2754146) - Admin SDKだけでは不可能と思われます。 – Grimthorr

+0

はい、私はこの方法を知っていますが、URLが非常に長いため、私はこの解決策が嫌いです。とにかく、これは唯一の方法だと思われます。 – SaroVin

関連する問題