【问题标题】:Send file to a folder in a bucket via storage client通过存储客户端将文件发送到存储桶中的文件夹
【发布时间】:2019-05-29 20:34:48
【问题描述】:

我正在关注文档,并且能够使用答案底部提供的代码(全部取自文档)成功地将图像文件发送到存储桶。该文件来自 Angular。

我现在尝试将此文件发送到同一存储桶中的特定文件夹,但无法正常工作。

const format = require('util').format;
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');
var cors = require('cors')
var morgan = require('morgan')
const fs = require('fs');
require('dotenv').config()
const { Storage } = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.use(morgan("short"));
app.use(cors())
app.use(bodyParser.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
    if (!req.file) {
        res.status(400).send('No file uploaded.');
        return;
    }

    // Create a new blob in the bucket and upload the file data.
    const blob = bucket.file(req.file.originalname)
    const blobStream = blob.createWriteStream();

    blobStream.on('error', (err) => {
        next(err);
    });

    blobStream.on('finish', () => {
        // The public URL can be used to directly access the file via HTTP.
        const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
        console.log('publicUrl', publicUrl);
        res.status(200).send({ message: publicUrl });
    });

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

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
    console.log('Press Ctrl+C to quit.');
});

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-storage


    【解决方案1】:

    您传递给bucket.file() 的字符串应该是目标文件的完整路径。现在你只是通过req.file.originalname。相反,构建一个完整的文件路径并传递该字符串。

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2016-01-17
      • 1970-01-01
      • 2013-03-30
      • 2016-11-16
      • 2020-06-09
      • 2020-07-30
      • 2021-11-21
      • 2011-07-27
      相关资源
      最近更新 更多