Reputation: 5529
I am following the documentation and have been able to successfully send an image file to a bucket using the code provided at the bottom of the answer (all taken from the documentation). The file is coming from Angular.
I am now trying to send this file to a particular folder in that same bucket but couldn't make it work.
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.');
});
Upvotes: 0
Views: 156
Reputation: 317322
The string you pass to bucket.file()
should be the full path of the destination file. Right now you are just passing req.file.originalname
. Instead, build a full file path and pass that string.
Upvotes: 2