Index Next: Cookies

File Uploads

Upload API

JaxServer handles file uploads in a semi-automated way by utilizing the NodeJS module formidable, more info is available here. Formidable makes it very easy to handle file uploads because it handles writing the data to disk automatically. JaxServer relays the file information using request.params like all other parameters.

Consider a web form with a file upload field name FILE:

<input type="file" name="FILE" />

The data can be retrieved in a controller route using the following API:

request.params.FILE.pathpath to the uploaded file
request.params.FILE.namethe name of the file provided by the web browser
request.params.FILE.typemime-type of the file

Upload Example

A form is created with a file upload field named myuploadfile:

Source of ~/jaxserver/app/helloworld/web/uploadform.html:
<html>
<head>
<title>Upload Form</title>
</head>
<body>

<form action="upload" method="post" enctype="multipart/form-data">
File: <input type="file" name="myuploadfile" /><br/>
<input type="submit">
</form>

</body>
</html>

A route is created to handle the upload by accessing request.params.myuploadfile and then moving the file into the application's /web/uploads/ directory to make it browsable.

function Helloworld() {
	/...
	this.post('/upload', 'upload');
}
//...
Helloworld.prototype.upload = function (request, response) {
	var app = this;
	if (request.params.myuploadfile) {
		jax.log.info('uploaded',request.params);
		var path = request.params.myuploadfile.path;
		var name = request.params.myuploadfile.name;
		var type = request.params.myuploadfile.type;
		var newlocation = this.webRoot+'/uploads/'+name;
		// move the uploaded file from ~/jaxserver/upload/ to /jaxserver/app/helloworld/web/uploads
		system.fs.rename(path, newlocation, function(e) {
			if (e) jax.server.sendError(request, response, 500, {error:e, message:'Upload error: could not rename file'});
			else {
				app.sendView(request,response,'upload', {
					name : name,
					url : app.urlPrefix+'/uploads/'+name,
					type : type
				});
			}
		});
		
	}
	else jax.server.sendError(request, response, 500, 'Upload error: no file');
};

The name, url, and mime-type of the uploaded file are sent to a view to display the uploaded file back to the user:

Source of ~/jaxserver/app/helloworld/views/upload.jxp:
<html>
<head>
<title>Upload</title>
<body>

<p>Here is your upload:

<p><a href="<%=url%>"><%=name%></a> (<%=type%>)

</body>
</html>

Try uploading a file to: http://localhost:8000/uploadform.html

Next: Cookies