add upload example

This commit is contained in:
TJ Holowaychuk 2013-11-27 20:44:17 -08:00
parent 81d027eca7
commit 4b5c3e9920
4 changed files with 90 additions and 1 deletions

51
examples/upload/index.js Normal file
View file

@ -0,0 +1,51 @@
/**
* Module dependencies.
*/
var logger = require('koa-logger');
var serve = require('koa-static');
var parse = require('co-busboy');
var koa = require('../..');
var fs = require('fs');
var app = koa();
// log requests
app.use(logger());
// custom 404
app.use(function *(next){
yield next;
if (this.body || !this.idempotent) return;
this.redirect('/404.html');
});
// serve files from ./public
app.use(serve(__dirname + '/public'));
// handle uploads
app.use(function *(next){
// ignore non-POSTs
if ('POST' != this.method) return yield next;
// multipart upload
var parser = parse(this);
var part;
while (part = yield parser.part()) {
var stream = fs.createWriteStream('/tmp/' + Math.random());
part.pipe(stream);
console.log('uploading %s -> %s', part.filename, stream.path);
}
this.redirect('/');
});
// listen
app.listen(3000);
console.log('listening on port 3000');

View file

@ -0,0 +1,15 @@
<html>
<head>
<title>Not Found</title>
<style>
body {
padding: 50px;
font: 14px Helvetica, Arial;
}
</style>
</head>
<body>
<h1>Sorry! Can't find that.</h1>
<p>The page you requested cannot be found.</p>
</body>
</html>

View file

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<style>
body {
padding: 50px;
font: 14px Helvetica, Arial;
}
</style>
</head>
<body>
<h1>File Upload</h1>
<p>Try uploading multiple files at a time.</p>
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>

View file

@ -37,7 +37,10 @@
"supertest": "~0.8.1",
"co-fs": "~1.1",
"co-views": "~0.1.0",
"ejs": "~0.8.4"
"ejs": "~0.8.4",
"koa-logger": "~1.0.1",
"koa-static": "~1.2.0",
"co-busboy": "git://github.com/cojs/busboy"
},
"engines": {
"node": "> 0.11.4"