gcs-upload
This is a simple express middleware to upload file from user to Google Cloud Storage.
It will change the field for the uploaded file with a url string like http://storage.googleapis.com/`bucket-name`/`filename` that you can save in database.
Requirements
- Make sure you have a google cloud project with billing enabled.
- Enable Google Storage API for the project.
- Create a service account and download the credential in JSON format.
Installation
npm install gcs-upload
Usage
options:
- limit: limits of uploaded data in object form (similar to limits option in multer)
- gcsConfig:
- keyFilename: file path for credential that you have downloaded before.
- bucketName: the bucket name that will contain the uploaded file, you can create one through google cloud console.
It will return an upload object that have 3 methods: (.single(), .array(), and .fields()). You can use all of it just like how you would use multer.
Basic Example
Don't forget the enctype="multipart/form-data" in your form.
<form action="/uploadSingle" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
const express = require('express')
const gcsUpload = require('gcs-upload')
const app = express()
const upload = gcsUpload({
limits: {
fileSize: 1e6
},
gcsConfig: {
keyFilename: '/Users/me/keyfile.json',
bucketName: 'myBucket'
}
})
app.post('/uploadSingle', upload.single('file'), (req, res) => {
console.log(req.body)
res.end()
})
app.post('/uploadArray', upload.array('files'), (req, res) => {
console.log(req.body)
res.end()
})
app.post('/uploadFields',
upload.fields([{ name: 'file1' }, { name: 'file2' }]),
(req, res) => {
console.log(req.body)
res.end()
}
)