ReferenceError: формат не определен при подключении к Firebase для загрузки файла - PullRequest
0 голосов
/ 11 июля 2020

Я пытаюсь подключиться к Firebase, чтобы загрузить файл и сохранить его в корзине. Вот код для этого:

const express = require('express');
const app = express();
const { Storage } = require('@google-cloud/storage');
const Multer = require('multer');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');

// Loads up the file
dotenv.config();

app.use(bodyParser.json());
app.set('view engine', 'ejs');

var admin = require("firebase-admin");
var serviceAccount = require('Path to the JSON file downloaded from the Service Accounts tab in Firebase');

admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "Link to the Firebase DB"
});


const storage = new Storage({
  projectId: "Project Id",
  keyFilename: 'Path to the JSON file downloaded from the Service Accounts tab in Firebase saved in a '.env' file'
});

const bucket = storage.bucket("Bucket Name");

const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 10 * 1024 * 1024
  }
});

// @route GET /
// @desc Loads form
// @update IT WAS MODIFIED TO RENDER THE FRONT PAGE WITH THE DATA COMING FROM THE DB USING gfs
app.get('/', (req, res) => {
   res.render('index');
});

/**
 * Adding new file to the storage
 */
app.post('/upload', multer.single('file'), (req, res) => {
  console.log('Upload Image');

  let file = req.file;
  if (file) {
    uploadImageToStorage(file).then((success) => {
      res.status(200).send({
        status: 'success'
      });
    }).catch((error) => {
      console.error(error);
    });
  }
});

/**
 * Upload the image file to Google Storage
 * @param {File} file object that will be uploaded to Google Storage
 */
const uploadImageToStorage = (file) => {
  return new Promise((resolve, reject) => {
    if (!file) {
      reject('No image file');
    }
    let newFileName = `${file.originalname}_${Date.now()}`;

    let fileUpload = bucket.file(newFileName);

    const blobStream = fileUpload.createWriteStream({
      metadata: {
        contentType: file.mimetype
      }
    });


    <--||||||||||||||||||| This is where the error occurs |||||||||||||||||||-->
    blobStream.on('error', (error) => {
      reject('Something is wrong! Unable to upload at the moment.' + error);
    });

    blobStream.on('finish', () => {
      // The public URL can be used to directly access the file via HTTP.
      const url = format(`https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`);
      resolve(url);
    });

    blobStream.end(file.buffer);
  });
}


app.listen(3000, () => {
  console.log('App listening to port 3000');
});

Несколько примечаний:

  • Это локальная настройка на моем p c, сервер не включен

  • Я использую vpn для доступа к Firebase, потому что моя страна заблокирована, может ли это быть проблемой?

  • Список пакетов:

    {"name": "NodeUploadFiles",

    "version": "1.0.0",
    "description": "",
    "main": "app.js",
    "scripts": {
      "start": "node app.js",
      "dev": "nodemon app.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
      "@google-cloud/storage": "^5.1.1",
      "body-parser": "^1.19.0",
      "dotenv": "^8.2.0",
      "ejs": "^3.1.3",
      "express": "^4.17.1",
      "firebase": "^7.16.0",
      "firebase-admin": "^8.13.0",
      "gridfs-stream": "^1.1.1",
      "method-override": "^3.0.0",
      "mongoose": "^5.9.22",
      "multer": "^1.4.2",
      "multer-gridfs-storage": "^4.2.0"
    },
    "devDependencies": {
      "nodemon": "^2.0.4"
    }
    

    }

...