0

A file is not being downloaded to the server from a html post.

Here is the koa server code 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');

Here is the index code sending the post 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>

Here is the console output:

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

As you can see, uploading is not stated and the file is not located on the server.

The directory upload exists at project/upload.

basickarl
  • 37,187
  • 64
  • 214
  • 335

1 Answers1

1

For HTML file uploads, the form has to have the attribute enctype="multipart/form-data" set.

And your file upload field needs to have a name set as well.

Also change:

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

to:

var stream = fs.createWriteStream(__dirname + '/upload/' + part.filename);
basickarl
  • 37,187
  • 64
  • 214
  • 335
CBroe
  • 91,630
  • 14
  • 92
  • 150