Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tus implementation - Final version
var tus = require("tus-js-client");
$('#uploadBtn').change(function () {
var file = this.files[0];
if (typeof file === "undefined") {
return;
}
// some validations goes here using `file.size` & `file.type`
var upload = new tus.Upload(file, {
// https://github.com/tus/tus-js-client#tusdefaultoptions
endpoint: "/tus",
retryDelays: [0, 1000, 3000, 5000, 10000],
overridePatchMethod: true, // Because production-servers-setup doesn't support PATCH http requests
chunkSize: 1000 * 1000, // Bytes
metadata: {
filename: file.name,
filetype: file.type
},
onError: function (error) {
// Handle errors here
},
onProgress: function (bytesUploaded, bytesTotal) {
// Reflect values on your progress bar using `bytesTotal` & `bytesUploaded`
},
onSuccess: function () {
// Upload has been completed
}
});
// Start the upload
upload.start();
});
<?php
class TusController {
public function indexAction() {
// Disable views/layout the way suites your framework
$server = $this->_getTusServer();
$response = $server->serve();
$this->_fixNonSecureLocationHeader($response);
$response->send();
}
private function _getTusServer() {
TusPhp\Config::set([
/**
* File cache configs.
*
* Adding the cache in the '/tmp/' because it is the only place writable by
* all users on the production server.
*/
'file' => [
'dir' => '/tmp/',
'name' => 'tus_php.cache',
],
]);
$server = new TusPhp\Tus\Server(); // Using File Cache (over Redis) for simpler setup
$server->setApiPath('/tus/index') // tus server endpoint.
->setUploadDir('/tmp'); // uploads dir.
return $server;
}
/**
* The `location` header is where the client js library will upload the file through,
* But, the load-balancer takes the `https` request & passes it as
* `http` only to the servers, which is tricking Tus server,
* so, we have to change it back here.
*
* @param type $response
*/
private function _fixNonSecureLocationHeader(&$response) {
$location = $response->headers->get('location');
if (!empty($location)) {// `location` is sent to the client only the 1st time
$location = preg_replace("/^http:/i", "https:", $location);
$response->headers->set('location', $location);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.