代码之家  ›  专栏  ›  技术社区  ›  Jacobo Koenig

在Javascript中从本地路径创建文件或Blob

  •  0
  • Jacobo Koenig  · 技术社区  · 6 年前

    我正在尝试将一些文件上载到Firebase存储,这需要一个文件或Blob对象。

    var file = ... // use the Blob or File API
    ref.put(file).then(function(snapshot) {
      console.log('Uploaded a blob or file!');
    });
    

    我在我的项目中有一个文件夹,里面有我要上传的所有文件,我正在尝试用它们的路径创建这样的对象。然而,我的尝试都没有成功。

    我尝试导入文件:

    let file = require('./Images/imagename.jpg');
    

    我研究了使用“fs”、文件API和其他选项,但似乎没有一种方法可以让我仅使用路径将文件放入对象。

    简而言之:有没有简单的方法从本地路径获取对象?

    1 回复  |  直到 6 年前
        1
  •  0
  •   colin    5 年前

    let bucket = admin.storage().bucket();
    let uploadRes = await bucket.upload(filePath, options);
    

    您可以在 google cloud storage docs . 您很可能会在google云控制台中创建一个具有权限的密钥,并将该文件导出为json。你会发现这个在 Google Cloud Platform console -&燃气轮机; IAM & admin Service accounts -&燃气轮机; Create service account

    export GOOGLE_APPLICATION_CREDENTIALS='./the_exported_file.json'

    请将此文件安全地存储在您的服务器上,因为它具有读写访问权限!

    <!-- language: typescript -->
    import admin from "firebase-admin";
    import path from 'path'
    const sha256File = require('sha256-file');
    
    const firebaseConfig = {
         apiKey: "...",
         authDomain: "abc.firebaseapp.com",
         databaseURL: "https://abc.firebaseio.com",
         projectId: "abc",
         storageBucket: "abc.appspot.com",
         messagingSenderId: "123",
         appId: "1:123:web:xxx",
         measurementId: "G-XXX"
    };
    
    admin.initializeApp(firebaseConfig);
    
    async function uploadFile(filePath: string, uploadFolder: string, contentType: string, hash: string | undefined = undefined,)
        : Promise<string> {
    
        if (!hash) {
            hash = await sha256File(filePath);
        }
        let bucket = admin.storage().bucket();
        const ext = path.extname(filePath);
        const uploadPath = uploadFolder + hash + ext;
        const options = {destination: uploadPath};
        console.debug("starting upload");
        let uploadRes = await bucket.upload(filePath, options);
        console.debug("finished upload");
    
        let newMetadata = {
            contentType: contentType
        };
        if(uploadRes) {
            let file = uploadRes[0];
            file.setMetadata(newMetadata).then(() => {
                // Updated metadata for 'images/forest.jpg' is returned in the Promise
            }).catch(function (error) {
                console.error(error)
            });
        }
    
        return uploadPath;
    }
    
        2
  •  -1
  •   Srujal Patel    6 年前

    首先告诉我你用哪种技术做前端。

    而不是创建FormData对象。

    如果你需要演示让我知道我可以帮助你。。。。