如何使用Admin API在Firebase Storage中创建文件夹

时间:2019-02-28 19:34:48

标签: firebase firebase-storage firebase-admin

  

目标:将文件上传到Firebase存储内的文件夹

例如

default_bucket/folder1/file1
default_bucket/folder1/file2
default_bucket/folder2/file3

使用Firebase 客户端,我可以像这样将文件上传到Firebase Storage中的文件夹:

    const storageRef = firebase.storage().ref();
    const fileRef = storageRef.child(`${folder}/${filename}`);
    const metadata = {
      contentType: file.type,
      customMetadata: { }
    };
    return fileRef.put(file, metadata);

如果该文件夹不存在,则会创建该文件夹。

  

但是我还没有使用Admin SDK来在同一服务器端进行操作。

下面的代码将文件上传到默认存储桶中。

但是,我想将文件上传到默认存储桶中的命名文件夹中。

客户端向GCF发出POST请求,发送文件和文件夹名称。

Busboy用于附加文件夹名称和文件,并将其传递给上传功能;会上传文件,然后返回文件的donwnload链接。

index.js

const task = require('./tasks/upload-file-to-storage');

app.post('/upload', (req, res, next) => {
  try {
    let uploadedFilename;
    let folder;

    if (req.method === 'OPTIONS') {
      optionsHelper.doOptions(res);
    } else if (req.method === 'POST') {
      res.set('Access-Control-Allow-Origin', '*');

      const busboy = new Busboy({ headers: req.headers });
      const uploads = [];

      busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
        uploadedFilename = `${folder}^${filename}`;

        const filepath = path.join(os.tmpdir(), uploadedFilename);
        uploads.push({ file: filepath, filename: filename, folder: folder });
        file.pipe(fs.createWriteStream(filepath));
      });

      busboy.on('field', (fieldname, val) => {
        if (fieldname === 'folder') {
          folder = val;
        } 
      });

      busboy.on('finish', () => {
        if (uploads.length === 0) {
          res.end('no files found');
        }
        for (let i = 0; i < uploads.length; i++) {
          const upload = uploads[i];
          const file = upload.file;

          task.uploadFile(helpers.fbAdmin, upload.folder, upload.file, uploadedFilename).then(downloadLink => {
            res.write(`${downloadLink}\n`);
            fs.unlinkSync(file);
            res.end();
          });
        }
      });
      busboy.end(req.rawBody);
    } else {
      // Client error - only support POST
      res.status(405).end();
    }
  } catch (e) {
    console.error(e);
    res.sendStatus(500);
  }
});

const api = functions.https.onRequest(app);

module.exports = {
  api
;

将文件上传到存储.js

exports.uploadFile = (fbAdmin, folder, filepath, filename) => {
  // get the bucket to upload to
  const bucket = fbAdmin.storage().bucket(); //`venture-spec-sheet.appspot.com/${folder}`

const uuid = uuid();
  // Uploads a local file to the bucket
  return bucket
    .upload(filepath, {
      gzip: true,
      metadata: {
        //destination: `/${folder}/${filename}`,
        cacheControl: 'public, max-age=31536000',
        firebaseStorageDownloadTokens: uuid
      }
    })
    .then(() => {
      const d = new Date();
      const expires = d.setFullYear(d.getFullYear() + 50);

      // get file from the bucket
      const myFile = fbAdmin
        .storage()
        .bucket()
        .file(filename);

      // generate a download link and return it
      return myFile.getSignedUrl({ action: 'read', expires: expires }).then(urls => {
        const signedUrl = urls[0];
        return signedUrl;
      });
    });
};

  

我尝试了一些事情

将存储桶名称设置为默认名称,并设置一个文件夹。这导致服务器错误。

const bucket = fbAdmin.storage().bucket(`${defaultName}/${folder}`); 

将存储桶名称设置为文件夹。这导致服务器错误。

const bucket = fbAdmin.storage().bucket(folder); 

而且,我还尝试使用 uploadOptions 的destination属性。 但这仍然会将文件放在默认存储桶中。

    .upload(filepath, {
      gzip: true,
      metadata: {
        destination: `${folder}/${filename}`, // and /${folder}/${filename}
      }
    })
  

是否可以使用Admin SDK上传到文件夹?

例如我想上传一个文件,将其放置在一个名为“文件夹”的文件中。

即所以我可以在以下路径引用文件:bucket / folder / file.jpg

在下面的示例中,每个“文件夹”都使用Firebase键命名。

enter image description here

1 个答案:

答案 0 :(得分:0)

  

发现了问题。   我愚蠢地在错误的位置声明了目标选项。

代替元数据对象:

 return bucket
    .upload(filepath, {
      gzip: true,
      metadata: {
        destination: `${folder}/${filename}`,
        cacheControl: 'public, max-age=31536000',
        firebaseStorageDownloadTokens: uuid
      }
    })

它应该已经在选项对象上:

 return bucket
    .upload(filepath, {
      gzip: true,
      destination: `${folder}/${filename}`,
      metadata: {   
        cacheControl: 'public, max-age=31536000',
        firebaseStorageDownloadTokens: uuid
      }
    })
  

通过此更改,文件现在被上传到名为“文件夹”的文件中。

相关问题