文件无法通过帖子上传到kojs

时间:2015-03-25 16:17:17

标签: post koa

文件未从html帖子下载到服务器。

以下是koa服务器代码project/app.js

'use strict';

/**
 * Module dependencies.
 */    
var logger = require('koa-logger');
var serve = require('koa-static');
var parse = require('co-busboy');
var koa = require('koa');
var fs = require('fs');
var app = koa();

// log requests
app.use(logger());

app.use(function* (next) {
    yield next;
    if (this.body || !this.idempotent) return;
    this.redirect('/');
});

// 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 parts = parse(this);
    var part;

    while (part =
        yield parts) {

        if (part.length) { // <--- I suspect this is to blame
            // arrays are busboy fields 
            console.log('key: ' + part[0])
            console.log('value: ' + part[1])
        } else {
            // otherwise, it's a stream 
            var stream = fs.createWriteStream('upload/' + part.filename);
            part.pipe(stream);
            console.log('uploading %s -> %s', part.filename, stream.path);
        }
    }

    this.redirect('/');
});

// listen    
app.listen(3000);
console.log('listening on port 3000');

以下是发送帖子project/public/index.html的索引代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Test</title>

    <base href="/">
</head>

<body>
    <form action="/" method="post" name="myform">
        <input type="file" multiple>
        <input name="firstName" value="harry" />
        <input name="lastName" value="tester" />
        <input name="toEmail" value="testtest@test.com" />
        <button type="submit" name="submit">Submit</button>
    </form>
</body>
</html>

这是控制台输出:

key: firstName
value: harry
key: lastName
value: tester
key: toEmail
value: testtest@test.com
key: submit
value: 
  --> POST / 302 18ms -
  <-- GET /
  --> GET / 200 8m

如您所见,未说明上传且该文件未位于服务器上。

目录upload存在于project/upload

1 个答案:

答案 0 :(得分:1)

对于HTML文件上传,表单必须设置属性enctype="multipart/form-data"

您的文件上传字段也需要设置name

同样改变:

var stream = fs.createWriteStream('upload/' + part.filename);

为:

var stream = fs.createWriteStream(__dirname + '/upload/' + part.filename);