Posted on Wednesday, March 18 2015 by Ionică Bizău
In this article I will describe how to upload files using Lien and Formidable, after creating a NodeJS HTTP server.
Lien is a tiny high-level framework for creating HTTP servers, being one of the libraries which power Bloggify.
Formidable is a NodeJS module for parsing form data and file uploads. We will use it to create a file upload interface in a Lien server.
First of all, create the directory structure:
# Create the project directory
$ mkdir file-upload
# Enter in the project directory
$ cd file-upload
# Create the public and uploads directories
$ mkdir -p public/uploads
Next, we have to install the dependencies:
$ npm i [email protected] [email protected]
Create the index.html
file into the public
directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input name="file" type="file">
<button>Submit</button>
</form>
<iframe src="/upload/list" frameborder="0"></iframe>
</body>
</html>
This is a HTML page containing a file upload form and an <iframe>
element which will list the uploaded files (/upload/list
).
And now the server side: index.js
// Dependencies
var Lien = require("lien")
, Fs = require("fs")
, Formidable = require("formidable")
;
// Constants
const DIR_UPLOADS = __dirname + "/public/uploads/";
// Init lien server
var server = new Lien({
host: "localhost"
, port: 9000
});
// Add page
server.page.add("/", function (lien) {
lien.file("/index.html");
});
// Upload
server.page.add("/upload$", function (lien) {
var form = new Formidable.IncomingForm(
{ uploadDir: DIR_UPLOADS }
);
form.parse(lien.req, function (err, fields, files) {
if (!files.file) {
return lien.end("File is missing.", 400);
}
Fs.rename(files.file.path, DIR_UPLOADS + files.file.name, function (err) {
if (err) {
return lien.end(err, 400);
}
lien.redirect("/");
});
});
});
// List
server.page.add("/upload/list", function (lien) {
Fs.readdir(DIR_UPLOADS, function (err, files) {
if (err) { return lien.end(err, 500); }
files = files.filter(function (c) {
return c !== ".gitignore";
});
var list = ["<ul>", files.map(function (c) {
return ["<li>", "<a target='blank' href='/uploads/", c, "'>", c, "</a></li>"].join("");
}).join(""), "</ul>"].join("");
lien.end(list);
});
});
And that's it. The server will run on localhost:9000
:
$ node index.js
Open localhost:9000
and there you can upload files and see a list with the previous uploads:
Browse the code here.
Have feedback on this article? Let @IonicaBizau know on Twitter.
Have any questions? Feel free to ping me on Twitter.