当前位置: 首页 > 知识库问答 >
问题:

无法从nodejs上传到google cloud或firebase存储桶

夏弘义
2023-03-14

我一直试图上传一些图像到我的firebase存储桶。我已经跟踪了这份官方文件:-

和https://googlecloudplatform.github.io/google-cloud-node/#/docs/storage/lates/storage/bucket

代码如下:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myprojectid.firebaseio.com/" , 
  storageBucket : "myprojectid.appspot.com/"
});

bucket = admin.storage().bucket() ; 
bucket.upload('./mylocalfile.jpg' , (err , file , response)=>{
console.log(err) ; //always gives me err
console.log(file) ; //gives undefined
}) ; 

但是bucket.getfiles().then(objects=>console.log(objects));工作得很好,可以打印根目录中的文件。

怎么解决这个?

以下是控制台日志记录时显示的错误err:

{ ApiError: Not Found
    at Object.parseHttpRespMessage (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\@google-cloud\common\src\util.js:156:33)
    at Object.handleResp (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\@google-cloud\common\src\util.js:131:18)
    at C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\@google-cloud\common\src\util.js:465:12
    at Request.onResponse [as _callback] (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\retry-request\index.js:179:7)
    at Request.self.callback (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:186:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:1163:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
  code: 404,
  errors: [],
  response:
   IncomingMessage {
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: true,
        endEmitted: true,
        reading: false,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain:
      Domain {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        members: [] },
     _events:
      { end: [Object],
        close: [Object],
        data: [Function],
        error: [Function] },
     _eventsCount: 4,
     _maxListeners: undefined,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: true,
        domain: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 4047,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [Object],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: null,
        read: [Function],
        _consuming: true,
        _idleTimeout: -1,
        _idleNext: null,
        _idlePrev: null,
        _idleStart: 1307656 },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: true,
        domain: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 4047,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [Object],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: null,
        read: [Function],
        _consuming: true,
        _idleTimeout: -1,
        _idleNext: null,
        _idlePrev: null,
        _idleStart: 1307656 },
     httpVersionMajor: 1,
     httpVersionMinor: 1,
     httpVersion: '1.1',
     complete: true,
     headers:
      { 'x-guploader-uploadid': 'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
        vary: 'Origin, X-Origin',
        'content-type': 'text/html; charset=UTF-8',
        'content-length': '9',
        date: 'Sat, 17 Mar 2018 13:24:19 GMT',
        server: 'UploadServer',
        'alt-svc': 'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' },
     rawHeaders:
      [ 'X-GUploader-UploadID',
        'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
        'Vary',
        'Origin',
        'Vary',
        'X-Origin',
        'Content-Type',
        'text/html; charset=UTF-8',
        'Content-Length',
        '9',
        'Date',
        'Sat, 17 Mar 2018 13:24:19 GMT',
        'Server',
        'UploadServer',
        'Alt-Svc',
        'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' ],
     trailers: {},
     rawTrailers: [],
     upgrade: false,
     url: '',
     method: null,
     statusCode: 404,
     statusMessage: 'Not Found',
     client:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: [Object],
        readable: true,
        domain: [Object],
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 4047,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [Object],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: null,
        read: [Function],
        _consuming: true,
        _idleTimeout: -1,
        _idleNext: null,
        _idlePrev: null,
        _idleStart: 1307656 },
     _consuming: true,
     _dumped: false,
     req:
      ClientRequest {
        domain: [Object],
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: false,
        upgrading: false,
        chunkedEncoding: true,
        shouldKeepAlive: true,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedHeader: [Object],
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'POST /upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile HTTP/1.1\r\nUser-Agent: gcloud-node-storage/1.4.0\r\nx-goog-api-client: gl-node/6.11.5 gccl/1.4.0\r\nAuthorization: Bearer ya29.c.<PLACEHOLDER_FOR_SOME_LONG_AUTH_ID>\r\nhost: www.googleapis.com\r\naccept-encoding: gzip, deflate\r\ntransfer-encoding: chunked\r\ncontent-type: multipart/related; boundary=6e012a90-2cb1-4c46-9de5-bb75cb5949ea\r\nConnection: keep-alive\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
        _ended: true,
        parser: null,
        timeoutCb: null,
        res: [Circular] },
     request:
      Request {
        domain: [Object],
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        timeout: 60000,
        gzip: true,
        forever: true,
        pool: [Object],
        method: 'POST',
        uri: [Object],
        headers: [Object],
        callback: [Function],
        readable: true,
        writable: true,
        explicitMethod: true,
        _qs: [Object],
        _auth: [Object],
        _oauth: [Object],
        _multipart: [Object],
        _redirect: [Object],
        _tunnel: [Object],
        setHeader: [Function],
        hasHeader: [Function],
        getHeader: [Function],
        removeHeader: [Function],
        localAddress: undefined,
        dests: [],
        __isRequestRequest: true,
        _callback: [Function: onResponse],
        proxy: null,
        tunnel: true,
        setHost: true,
        originalCookieHeader: undefined,
        _disableCookies: true,
        _jar: undefined,
        port: 443,
        host: 'www.googleapis.com',
        url: [Object],
        path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
        httpModule: [Object],
        agentClass: [Object],
        agentOptions: [Object],
        agent: [Object],
        src: [Object],
        _started: true,
        href: 'https://www.googleapis.com/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
        req: [Object],
        ntick: true,
        response: [Circular],
        originalHost: 'www.googleapis.com',
        originalHostHeaderName: 'host',
        responseContent: [Circular],
        _destdata: true,
        _ended: true,
        _callbackCalled: true },
     toJSON: [Function: responseToJSON],
     caseless: Caseless { dict: [Object] },
     read: [Function],
     body: 'Not Found' },
  message: 'Not Found' }

共有1个答案

谭思博
2023-03-14

不幸的是,Upload函数只能接收到本地文件或url的路径,因此在用云函数实现上传文件REST api时会带来一些复杂性。我猜把文件上传到云功能服务器和把本地文件上传到云存储应该不是一个合适的方式。

以下是我使用multer从请求中获取文件,然后将其转换为数据,并使用save函数上传的方法,使上传endpoint到firebase(gcloud)存储。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const multer  = require('multer');
const app = express();
const fileUpload = multer();

admin.initializeApp(.......);

/*
 * Upload File
 **/
app.post('/', fileUpload.single('file'), functions.https.onRequest((req, res) => {
  const file = req.file;
  const bucket = admin.storage().bucket();
  const name = file.originalname;
  
  const bucketFile = bucket.file(name);

  bucketFile
    .save(new Buffer(file.buffer))
    .then(() => {
      res.status(200).json({
        status: 'success',
        data: Object.assign({}, bucketFile.metadata, {
          downloadURL: `https://storage.googleapis.com/${bucket.name}/${name}`,
        })
      });
    })
    .catch(err => {
      res.status(500).json({
        status: 'error',
        errors: err,
      });
    });
}));
 类似资料:
  • 我试图构建一个,它包括两个按钮,一个用于用相机拍照并上传到Firebase存储,另一个用于从Firebase存储下载图像并在上显示。 现在,我被上传功能卡住了。我可以把照片保存到应用程序目录中。我想上传保存的图片到Firebase存储。

  • 我有一个firebase帐户,我想以编程方式上传一些照片到firebase存储。为此,我使用了google cloud java storage API。我配置权限和其他权限。我可以成功地创建桶,斑点。然而,当我试图上传一张图片时,要么它的大小为0,要么它无法下载(不生成URL)。下面是我使用的代码; 任何建议都很感激。问候。

  • 我正在尝试上传图像到firebase,以及其他字符串和双数据类型。 我现在正在考虑两个选项,一个是上载imageUrl到firebase实时数据库,当我检索它时,我将检索一个imageUrl并将其转换为图像。 谢谢你的帮助!我很感激。

  • 我有一个问题与我的代码,我必须上传图像到Firebase存储,我需要的图像来自画廊和相机,从画廊的图像是好的,但来自相机的图像给问题,图像加载在ImageView和被发送到数据库是黑色的。有人知道如何解决这个问题吗,或者你知道任何其他加载图像的方法吗? 来自画廊 从相机

  • 我从Firebase存储中获取图像,用相机拍照,或者从图书馆中挑选一张。当其中一个完成时,我有一个类来存储,以便在需要时使用它。 现在我需要将此图像上传到Firebase存储(修改或新建,无所谓)。Firebase允许我使用以下选项之一:或,每个选项分别需要或。 我怎么能把我的,并从它获得一个或用于上传? -- 或者,为了解决这个问题,当我从Firebase存储中检索图像时,如何获取图像的? 无论

  • 我在我的网站上有一个处理文件上传的页面,但是自从我升级了Firebase(我猜是Firebase v7/8)后,这个特殊的功能不再工作了。 为了在firebase存储中处理文件上载,我创建了一个自定义钩子,在这里我使用,因为每次有新的文件值时都需要运行它。我为试图上载的文件传递了一个参数(),并将其存储在数据库中,这样数据库就包含了所有图像的url。然后,我使用这些数据将图像加载到react组件中