从URL下载图像,保存到Firebase Store,并提供图像URL



我很难找到一些代码来完成这项工作,而且我自己在尝试实现这项工作时也遇到了麻烦。我想创建Firebase函数,它将调用一个映像URL(此URL具有来自Mapbox的与其关联的令牌(。然后我想把图像写入Firebase Storage,这样我以后就可以从那里引用它来提供它。到目前为止,我已经想好了如何获取图像,但把它保存到存储中似乎对我来说太难了!帮助

exports.getPolylineFromSessionId = functions.https.onRequest(async (req, res) => {
    const sessionId = req.query.id;
    if (sessionId) {
        const sessionInfo = await db
            .collection('sessions')
            .doc(sessionId)
            .get();
        const session = sessionInfo.data();
        const results = encodeURIComponent(polyline.encode(convertGpsTrack(session.gpsTrack)));
        const url =
            'https://api.mapbox.com/styles/v1/mapbox/satellite-v9/static/path-1+fff-0.5(' + results + ')/auto/700x200?access_token=' + mapboxToken;
         const bucket = admin
            .storage()
            .bucket('gs://mybucket.appspot.com')
            .file('thumbnails/' + sessionId + '.jpg');
         const res = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'image/jpeg',
            },
         });
         const blob = await res.blob();
         bucket.save(blob, {
            metadata: {
                contentType: 'image/jpeg',
            },
         });
        res.status(200).send(session);
    } else {
        res.status(400).send('sessionId required');
    }
});

我终于想明白了!下面是我使用的代码!

var file = admin
    .storage()
    .bucket('gs://mybucket.appspot.com')
    .file('thumbnails/' + sessionId + '.jpg');
request({ url: url, encoding: null }, function(err, response, buffer) {
    var stream = file.createWriteStream({
        metadata: {
            contentType: response.headers['content-type'],
        },
    });
    stream.end(buffer);
});

相关内容

  • 没有找到相关文章

最新更新