[英]How to upload canvas to project's folder using javascript and mvc
[英]Upload folder(s) on firebase - javascript
我們可以在 firebase 存儲上上傳空文件夾或簡單地上傳包含許多文件的文件夾嗎?
因為實際上我可以上傳一個文件,但也可以上傳多個文件,但我沒有找到如何使用文件夾。
我建議你去谷歌雲(Firebase 項目也在谷歌雲中),並在那里檢查你的存儲桶。 您將能夠在那里看到一個上傳文件夾選項,您可以使用它通過 GUI 上傳文件夾。 如果您願意,您可以拖放多個文件夾。
無法一次性將整個文件夾上傳到 Cloud Storage for Firebase。 您必須上傳文件夾中的各個文件。
Cloud Storage for Firebase 中沒有空文件夾的概念。 文件夾僅存在於其中包含文件的事實。
另見:
要以編程方式執行此操作,最好的解決方案是:
(1) 遞歸獲取要上傳的文件夾中所有文件的列表
(2) 使用 Promise.all 一鍵上傳所有文件
這種方法有效,尤其是因為 firebase 為您創建了缺失的存儲路徑
(1) 和 (2) 的代碼(用 TS 編寫)如下
遞歸獲取文件列表
import { Dirent, readdirSync } from 'fs'
import path from 'path'
import { IPath } from '../interfaces/i-path'
import { escapeRegExp } from 'lodash'
interface IDirent {
dirent: Dirent
path: string
}
const getAllFiles = (dir: string): IDirent[] => {
const dirents: IDirent[] = readdirSync(dir, { withFileTypes: true }).map((dirent: Dirent) => ({ dirent, path: path.resolve(dir, dirent.name) }))
return dirents.reduce((acc: IDirent[], dirent: IDirent) => {
if (dirent.dirent.isDirectory()) return [...acc, ...getAllFiles(dirent.path)]
if (dirent.dirent.isFile()) return [...acc, dirent]
return acc
}, [])
}
export const getAllFilesInFolder = (dir: string): IPath[] => {
const regex = new RegExp(`^${escapeRegExp(dir)}`)
return getAllFiles(dir).map((dirent: IDirent) => {
let shortPosixPath: string = dirent.path.replace(regex, '')
shortPosixPath = shortPosixPath.split(path.sep).join(path.posix.sep)
if (shortPosixPath.startsWith(path.posix.sep)) shortPosixPath = shortPosixPath.substring(1)
return { fullPath: dirent.path, shortPosixPath }
})
}
一鍵上傳所有文件
import os from 'os'
import { getAllFilesInFolder } from '../../utils/get-all-files-in-folder'
import { IPath } from '../../interfaces/i-path'
import admin from 'firebase-admin'
import { getObjectPath } from '../../utils/string-utils'
import path from 'path'
import * as functions from 'firebase-functions'
// the following code will live inside some function
const storageBasePath = 'videos-out/test-videos/video-14/hls'
const dir: string = '/temp/my-folder-to-upload'
const files: IPath[] = getAllFilesInFolder(dir)
// object.bucket is just a string and is the bucket you are uploading to - e.g. something.appspot.com
const promises = files.map((file: IPath) => {
const destination = `${storageBasePath}/${file.shortPosixPath}`
return admin.storage().bucket(object.bucket).upload(file.fullPath, { destination })
})
Promise.all(promises).then(
() => console.log('success')
).catch(
() => console.log('failure')
)
最后,接口IPath很簡單
export interface IPath {
fullPath: string
shortPosixPath: string
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.