首页 > 解决方案 > 通过存储客户端将文件发送到存储桶中的文件夹

问题描述

我正在关注文档,并且能够使用答案底部提供的代码(全部取自文档)成功地将图像文件发送到存储桶。该文件来自 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.jsgoogle-cloud-platformgoogle-cloud-storage

解决方案


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


推荐阅读