Skip to content

Instantly share code, notes, and snippets.

@Abdelhady
Last active November 16, 2018 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abdelhady/c5d7f0f70d2df3435c7b289eec1bea74 to your computer and use it in GitHub Desktop.
Save Abdelhady/c5d7f0f70d2df3435c7b289eec1bea74 to your computer and use it in GitHub Desktop.
Traditional way of uploading files
$('#uploadBtn').change(function () {
var file = this.files[0];
if (typeof file === "undefined") {
return;
}
// some validations goes here using `file.size` & `file.type`
var myFormData = new FormData();
myFormData.append('videoFile', this.files[0]); // `videoFile` is the file name expected at the backend
$.ajax({
url: '/file/post',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: myFormData,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', handleProgressBar, false); // For handling the progress of the upload
}
return myXhr;
},
success: function(){
// Upload has been completed
}
});
});
function handleProgressBar(e) {
if (e.lengthComputable) {
// reflect values on your progress bar using `e.total` & `e.loaded`
}
}
<?php
class FileController {
public function postAction() {
// Disable views/layout the way suites your framework
if (!isset($_FILES['imageFile'])) {
// Throw an exception or handle it your way
}
// Nginx already did all the work for us, & received the file in the `/tmp` folder
$uploadedFile = $_FILES['imageFile'];
$OriginalFileName = $uploadedFile['name'];
$size = $uploadedFile['size'];
$completeFilePath = $uploadedFile['tmp_name'];
// Do some validations on file's type & file's size (using `$size` & `filesize($filePath)`
// & if all is fine, then start processing your file here, & probably return a success message
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment