node.js - 通过存储客户端将文件发送到存储桶中的文件夹
问题描述
我正在关注文档,并且能够使用答案底部提供的代码(全部取自文档)成功地将图像文件发送到存储桶。该文件来自 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.');
});
解决方案
您传递给的字符串bucket.file()
应该是目标文件的完整路径。现在你只是路过req.file.originalname
。相反,构建一个完整的文件路径并传递该字符串。
推荐阅读
- python - 比较不同csv文件中不同行的2列,并将状态输出到另一个csv文件
- java - 如何在使用 Spring 会话的项目中设置忽略 URL
- c - 从 vmlinux 二进制文件中获取特定设备驱动程序 c 文件名和查看代码的名称
- python - 我想在 UCF_CC_50 数据集上训练 CSRNet 模型,该数据集的图像总数为 50。并面临类似的问题
- spring-boot - 休眠 OnetoMany 与 Fetch Lazy 给 LazyInitializationException
- json - Firebase Flutter Dart:类“_JsonQuerySnapshot”没有实例方法“[]”。接收方:“_JsonQuerySnapshot”的实例
- oracle - OBIEE RPD:雪花表未在 BMM 层中显示为事实表
- python - 如何获取列表中str和int元素组合的最小值
- ios - Xcode 12.1 中的 errSecInternalComponent 错误
- c# - 如何在统一动作闭包中访问游戏对象