'How to use formidable npm to upload files to Google Cloud
I tried to upload files to my Google Cloud bucket using formidable (using the example at https://www.npmjs.com/package/formidable-serverless?activeTab=readme ) but still couldn't get it uploaded on my bucket.
This is my .env file
GCS_BUCKET = <bucket-name>
GCLOUD_PROJECT = <project-name>
GCS_KEYFILE = <key file location>
This is what I tried
const formidable = require('formidable-serverless');
const http = require('http');
const util = require('util');
http.createServer(function(req, res) {
if (req.url == 'gs://<bucket-name>/' && req.method.toLowerCase() == 'post') {
// parse a file upload
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
I also tried Mutler (https://www.npmjs.com/package/multer-google-storage) , can anyone help with working examples
Solution 1:[1]
I know it's a late post.
Just not to keep the question unanswerable.
const express = require('express');
const formidable = require('formidable');
const { Storage } = require('@google-cloud/storage');
const bucket = 'yourBucketName';
async function uploadFile(bucket, filename) {
const storage = new Storage();
const params = { metadata: { cacheControl: 'public, max-age=31536000' }
};
await storage.bucket(bucket).upload(filename, params);
console.log(`${filename} uploaded to ${bucket}.`);
}
const app = express();
app.get('/', (req, res) => {
res.send(`
<h2>With <code>"express"</code> npm package</h2>
<form action="/api/upload" enctype="multipart/form-data" method="post">
<div>Text field title: <input type="text" name="title" /></div>
<div>File: <input type="file" name="someExpressFiles" multiple="multiple" /></div>
<input type="submit" value="Upload" />
</form>
`);
});
app.post('/api/upload', (req, res, next) => {
const form = formidable();
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
let imgPath = files.someExpressFiles.path;
uploadFile(bucket, imgPath).catch(console.error);
res.json({ fields, files });
});
});
app.listen(8080, () => {
console.log('Server listening on http://localhost:8080 ...');
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | patric_cena |
