Reputation: 33
I am making an image upload app with Node, Koa2, Mongo, GridFS, and React. Currently I have no problem uploading files with this code:
// HANDLE POST MULTIPART FORM DATA
app.use(async function(ctx, next) {
if (
!ctx.request.is('urlencoded', 'multipart') ||
('POST' != ctx.method && ctx.url === '/uploadFiles')
) return await next()
console.log('POST REQUESTED AT: ', ctx.url)
// HANDLE THIS MIME TYPE SOME OTHER WAY!!!!
var mimeTyp = ''
// WAIT UNTIL CONNECTION IS RESOLVED
const conn = await connectionDB()
// SETUP THE MAIN DATABASE
const testDB = conn.db('gridfsTestDB')
// SETUP FS.FILES CONNECTION
const fsFiles = testDB.collection('fs.files')
// SET THE BUCKET FOR GRIDFS
const bucket = new mongodb.GridFSBucket(testDB)
// DECLARE WHERE YOU WANT THE FILE TO BE UPLOADED AND YOU CAN SUPPLY ADITIONAL DATA HERE TO THE FILE
const writeStream = bucket.openUploadStream()
const readStream = bucket.openDownloadStream()
console.log(readStream)
// ASYNC-BUSBOY MIDDLEWARE HANDLES FORM SUBMITION AND FILE PIPEING
const { fields } = await AsyncBusboy(ctx.req, {
// THIS IS CALLED FOR EACH CHUNK OF FILE SENT THROUGH PIPE
onFile: function(fieldname, file, filename, encoding, mimetype) {
console.log('start pipe')
console.log('MIMETYPE', mimetype)
mimeTyp = mimetype
file.pipe(writeStream)
console.log('end pipe')
}
})
// HERE WE WAIT FOR STREAM OF THE FILE TO FINISH AND THEN WE APPEND METADATA TO IT
await onStreamFinish(writeStream)
})
But I have a problem reading the file from Mongo and showing it to the user. How would one do this with async approach? createReadStream
I figure but had no luck implementing it. I am just looking for guidance on what to use and I will try it.
EDIT(thanks to Rich Churcher) :
try {
const conn = await connectionDB()
const testDB = conn.db('gridfsTestDB')
const fsFiles = testDB.collection('fs.files')
const bucket = new mongodb.GridFSBucket(testDB)
const metadataFile = await getfileToDownload(ctx.params.id, fsFiles)
const readStream = bucket.openDownloadStream(ObjectId(ctx.params.id))
console.log(metadataFile)
ctx.set('Content-Type', metadataFile.contentType)
ctx.set(
'Content-Disposition',
'inline; filename="' + normalizeString(metadataFile.metadata.DocumentName) + '"'
)
ctx.body = readStream
} catch (err) {
console.log(err)
ctx.status = 503
ctx.body = {
message: 'Unable to preview the document. Error: ' + err.message
}
}
Works just fine!
Upvotes: 3
Views: 2333
Reputation: 7654
One of the Koa examples is stream-file, which is a good starting point. Usually it's just a case of setting ctx.body
to the stream. Obviously you want to use GridFS as the source rather than the local file system.
I note gridfs-stream, which I think would make life easier for you. However, let's assume you don't want to add another dependency. Here's the bare minimum handler for a download:
const { GridFSBucket, MongoClient } = require('mongodb')
// ...
app.use(async ctx => {
const connection = await MongoClient.connect('mongodb://localhost:27017')
const db = connection.db('gfs-example')
const bucket = new GridFSBucket(db, { bucketName: 'images' })
ctx.type = 'image/jpg'
ctx.body = bucket.openDownloadStreamByName('foo.jpg')
})
It looks like you already have your own database tooling set up, I'm just including a connection to make this answer more self-contained. Note that setting ctx.type
isn't strictly necessary to get the file, but it helps indicate to the browser that it should display the image rather than treat it as a download.
Upvotes: 1