我正在关注文档,并且能够使用答案底部提供的代码成功地将图像文件发送到存储桶(全部取自文档)。该文件来自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.');
});
答案 0 :(得分:2)
您传递给bucket.file()
的字符串应该是目标文件的完整路径。现在,您正在传递req.file.originalname
。相反,构建完整的文件路径并传递该字符串。