ForgejComponent
en

jComponent

Upload files with UPLOAD() and progress

jComponent 20 · jcomponent@20 jcomponentfrontenduploadfiles Executed with jComponent 20

UPLOAD('POST /url/', formdata, callback, onprogress) posts a FormData (the address starts with the HTTP method, like in AJAX()) and calls the callback with the parsed response. The optional fourth argument receives the percentage while the upload runs. Build the FormData from a file input (new FormData() and append('file', input.files[0])); the server side is the @upload route of the file upload recipe.

controllers/upload.js
exports.install = function() {
	ROUTE('POST /upload/ @upload <5mb', upload);
};

function upload($) {

	var file = $.files[0];

	file.read(function(err, buffer) {
		$.json({ filename: file.filename, text: buffer.toString('utf8'), title: $.body.title });
	});
}
public/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>jComponent</title>
	<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
	<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
	<script>

		var form = new FormData();
		form.append('title', 'My note');
		form.append('file', new Blob(['hello from the browser'], { type: 'text/plain' }), 'note.txt');

		var progress = [];

		UPLOAD('POST /upload/', form, function(response) {
			SET('uploaded', response);
		}, function(percentage) {
			progress.push(percentage);
		});

	</script>

</body>
</html>
Try it in your browser

Edit the example and run it. It runs in an isolated frame in your browser; nothing is sent to our server.

Preview