Create File or Blob from local path in Javascript
Asked Answered
M

3

6

I have extensively and systematically searched for an answer in stack overflow but haven't been able to find one that fits my needs.

I am trying to upload a number of files to Firebase Storage, which requires a File or Blob object.

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

I have a folder in my project with all the files I want to upload, and I'm trying to create such objects with their paths. However, none of my attempts have worked.

I tried importing the file:

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

and I researched using 'fs', the File API and other options, but none seem to have a way for me to get the file into an object using only the path.

In short: is there any simple way to get the object from a local path?

Marxist answered 7/4, 2019 at 14:13 Comment(1)
fs.readFile() will get you a Buffer object which you can pass to the http request methods to send itAvidin
S
1

Here is how you can upload a file from the drive to Firebase Storage:

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

You can find a description of the option in the google cloud storage docs. You will most likely create a key in the google cloud console with permissions and export the file as a json. You will find this in the Google Cloud Platform console -> IAM & admin -> Service accounts -> Create service account (create it with a key). Once you exported the json, set the environment variable like this:

export GOOGLE_APPLICATION_CREDENTIALS='./the_exported_file.json'

PLEASE STORE THIS FILE SECURELY ON YOUR SERVER AS IT HAS READ AND WRITE ACCESS!

Below is a full example of an upload function that also saves the file under it's hash name.

<!-- 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;
}
Swordplay answered 19/11, 2019 at 2:0 Comment(0)
F
0

This should work in recent versions of Node.js:

import fs from "fs";
import { Blob } from "buffer";

let buffer = fs.readFileSync("./your_file_name");
let blob = new Blob([buffer]);
Furnishing answered 3/4, 2022 at 16:13 Comment(0)
K
-1

First of all tell me that which technology you're using for front-end.

If you are using angular than you just need to get $event every time like change event. than you need to create FormData object. Pass that object into node and node side use multer for storing the file.

if you need the demo let me know I can help you....

Kenwrick answered 7/4, 2019 at 14:24 Comment(1)
Pure javascript and nodejsMarxist

© 2022 - 2024 — McMap. All rights reserved.