-
-
Save interjc/a9a68e5989a86f84f6277b88fabaee4a to your computer and use it in GitHub Desktop.
Streaming uploads through Koa.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Koa from 'koa' | |
import parse from './busboy' | |
import AWS from 'aws-sdk' | |
const app = new Koa() | |
const s3 = new AWS.S3({ | |
params: { Bucket: 'myBucket' } | |
}) | |
// Assuming this is a route handler. | |
app.use(async (ctx) => { | |
const { file, filename } = await parse(ctx.req) | |
// `file` is a Stream. Pass this to S3, Azure Blob Storage or whatever you want. | |
// `filename` is the file name specified by the client. | |
const result = await s3.upload({ | |
Key: filename, | |
Body: file | |
}).promise() | |
ctx.body = result | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Busboy from 'busboy' | |
/** | |
* Parses a single file from a Node request. | |
* | |
* @param {http.IncommingRequest} req | |
* @return {Promise<{ file: Stream, filename: string>} | |
*/ | |
export default function parse (req) { | |
return new Promise((resolve, reject) => { | |
const busboy = new Busboy({ | |
headers: req.headers, | |
limits: { | |
files: 1 // allow only a single upload at a time. | |
} | |
}) | |
busboy.once('file', _onFile) | |
busboy.once('error', _onError) | |
req.pipe(busboy) | |
function _cleanup () { | |
busboy.removeListener('file', _onFile) | |
busboy.removeListener('error', _onError) | |
} | |
function _onFile (fieldname, file, filename) { | |
_cleanup() | |
resolve({ file, filename }) | |
} | |
function _onError (err) { | |
_cleanup() | |
reject(err) | |
} | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `file` is a DOM File object. | |
function upload (file) { | |
const data = new window.FormData() | |
data.append('file', file, file.name) | |
return axios.post('/upload', data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment