node.js - multipart File uploads using NodeJS -
i having troubles getting file uploads work nodejs. using dropzone.js create form sends post request /file-upload here:
<form action="/file-upload" class="dropzone dragndrop" id="my-awesome-dropzone"></form>
then have route in app.js:
app.post('/file-upload', routes.upload);
then handler:
exports.upload = function(req, res){ console.log(req.files); res.send("ok"); }
however, upload function here never called. server crashes error first:
events.js:69 throw arguments[1]; // unhandled 'error' event ^ error: invalid data @ writestream._write (fs.js:1616:31) @ onwrite (_stream_writable.js:265:14) @ writablestate.onwrite (_stream_writable.js:94:5) @ fs.js:1628:5 @ object.wrapper [as oncomplete] (fs.js:475:5) @ process._makecallback (node.js:321:24)
so not sure should because appears not fault. followed other tutorials , saw nothing wrong. also, when inspect network under chrome dev tools, shows:
request url:http://localhost:3000/file-upload **request headers** accept:application/json cache-control:no-cache content-type:multipart/form-data; boundary=----webkitformboundarymmlskbfqskficjfe origin:http://localhost:3000 pragma:no-cache referer:http://localhost:3000/ user-agent:mozilla/5.0 (x11; linux i686) applewebkit/537.17 (khtml, gecko) chrome/24.0.1312.52 safari/537.17 x-file-name:screenshot 2013-03-20 12:23:42.png x-requested-with:xmlhttprequest **request payload** ------webkitformboundarymmlskbfqskficjfe content-disposition: form-data; name="file"; filename="screenshot 2013-03-20 12:23:42.png" content-type: image/png ------webkitformboundarymmlskbfqskficjfe--
@user568109 , @nick-fishman correct; should use bodyparser middleware this.
please see sample code basic file upload form below. (note: need create "uploads" directory store files.)
file-upload.js:
var express = require("express"), app = express(); // tell express use bodyparser middleware // , set upload directory app.use(express.bodyparser({ keepextensions: true, uploaddir: "uploads" })); app.engine('jade', require('jade').__express); app.post("/upload", function (request, response) { // request.files contain uploaded file(s), // keyed input name (in case, "file") // show uploaded file name console.log("file name", request.files.file.name); console.log("file path", request.files.file.path); response.end("upload complete"); }); // render file upload form app.get("/", function (request, response) { response.render("upload_form.jade"); }); app.listen(3000);
views/upload_form.jade:
doctype 5 html head title upload form body h1 upload file form(method="post", action="/upload", enctype="multipart/form-data") input(type="file", name="file") input(type="submit")
Comments
Post a Comment