上传文件及上传进程

上传文件可以用formidable模块,代码如下

var http = require('http')
var formidable = require('formidable')
var items = []
var server = http.createServer(function (req, res) {
    if( '/' === req.url){
        switch (req.method){
            case 'GET':
                show(res);
                break;
            case 'POST':
                upload(req, res)
                break;
            default:
                badRequest(res)
        }
    }else {
        notFound(res)
    }
})
server.listen(3000)

function show(res) {
    console.log(items)
    var html = '<html><head><title>todo list</title></head><body>' +
        '<h1>todo list</h1>' +
        '<ul>' +
        items.map(function(item){
            return '<li>'+item+'</li>'
        }).join('') +
        '</ul>' +
        '<form method="post" action="/" enctype="multipart/form-data">' +
        '<p><input type="text" name="item"></p>' +
        '<p><input type="file" name="file"></p>' +
        '<p><input type="submit" value="add item"></p>' +
        '</form>' +
        '</body></html>'

    res.setHeader('Content-Type', 'text/html')
    res.setHeader('Content-Length', Buffer.byteLength(html))
    res.end(html)

}
function notFound (res){
    res.statusCode = 404
    res.setHeader('Content-Type', 'text/plain')
    res.end('not found')
}
function badRequest(res) {
    res.statusCode = 400
    res.setHeader('Content-Type', 'text/plain')
    res.end('Bad Request')

}
var qs = require('querystring')
function add(req, res) {
    var body = ''
    req.setEncoding('utf8')
    req.on('data', function (chunk) {
        console.log(chunk)
        body += chunk
    })
    req.on('end', function () {
        var obj = qs.parse(body)
        items.push(obj.item)
        show(res)
    })
}
function upload(req, res) {
    if(!isFormData(req)) {
        res.statusCode = 400
        res.end('Bad request')
        return
    }
    var form = new formidable.IncomingForm()
    form.on('progress', function (bytesReceived, bytesExpected) {
        var percent = Math.floor(bytesReceived / bytesExpected * 100)
        console.log(percent)

    })
    form.parse(req, function (err, fields, files) {
        res.end('up c')
    })
}
function isFormData(req) {
    var type = req.headers['content-type' || '']
    return 0 == type.indexOf('multipart/form-data')
}

随机浏览