繁体   English   中英

Firebase 存储 | 从 node.js 云函数上传时文件是“application/octet-stream”

[英]Firebase Storage | File is "application/octet-stream" on upload from node.js cloud function

问题

我有一个可调用的云函数,它使用 Sharp 生成缩略图,然后将它们上传到 Firebase 存储

const { getStorage } = require('firebase-admin/storage');
const bucket = getStorage().bucket();

const filePath = ref;
    const workingDir = join(tmpdir(), 'thumbs');
    const downloadedFilePath = join(workingDir, 'source');
    const destinationDir = getThumbDir(dirname(filePath));

    // 1. Ensure thumbnail dir exists
    await ensureDir(workingDir);

    // 2. Download Source File
    await bucket.file(filePath).download({
        destination: downloadedFilePath,
    });

    const sizes = [100, 200, 300]

    const uploadPromises = sizes.map(async size => {
        const thumbName = `@${size}.jpg`;
        const thumbPath = join(workingDir, thumbName);
        const destinationPath = `${destinationDir}/${thumbName}`

        // Resize source image
        await sharp(downloadedFilePath)
            .resize(size, size)
            .toFile(thumbPath);
        
        
        // Upload to GCS
        return await bucket.upload(thumbPath, {
            destination: destinationPath,
            contentType: "image/jpeg",
            
        });
    });

    // 4. Run the upload operations
    await Promise.all(uploadPromises);
    await remove(workingDir);

问题是这些文件在我的数据库中都显示为“application/octet-stream”类型。 为什么是这样? 请注意,我正在为所有这些使用完整的本地 firebase 模拟器,这会产生影响吗?

细节

using node.js
firebase tools 11.16.0
firebase-admin": "^11.2.1
sharp: ^0.31.1

bucket.upload()的第二个参数名为options并且没有属性contentType 它可能只是被忽略了。 文档: https ://googleapis.dev/nodejs/storage/latest/global.html#UploadOptions

您实际上对options.metadata.contentType感兴趣。 所以你应该像这样修复你的代码:

        // Upload to GCS
        return await bucket.upload(thumbPath, {
            destination: destinationPath,
            metadata: {
                contentType: "image/jpeg",
            },            
        });

application/octet-stream类型是默认的,这基本上意味着格式是未知的。 调试 mime 类型可能会令人沮丧,因为某些工具( gsutil和我认为是 GCS 控制台)可以在上传期间从文件名中检测到类型; 因此手动重现问题并不简单。 文档: https ://cloud.google.com/storage/docs/metadata#content-type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM