Skip to content

Instantly share code, notes, and snippets.

@mayeenulislam
Last active June 4, 2020 11:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayeenulislam/bde162683ccb9899c0a4756fd98edb52 to your computer and use it in GitHub Desktop.
Save mayeenulislam/bde162683ccb9899c0a4756fd98edb52 to your computer and use it in GitHub Desktop.
This is a demonstration (aka demo) of the setup of jQuery File Upload in a standalone file input. We're *not using* the `UI version` and the default validation was not working for us, so we ditched those and followed community provided raw checkup. Thanks to the StackOverflow thread for guiding to achieve my need: https://stackoverflow.com/q/174…
<!--
jQuery File Upload UI
jQuery File Upload is a huge plugin with a lot of functionalities.
And that made this a bit complex to find out how to implement a
basic upload feature like:
1. Multiple file upload
2. Validate on file types
3. Validate on file size
4. Validate whether maximum number of files reached or not
5. Display progress
6. See the uploaded file before the form submission
7. Delete uploaded file
This is just a front-end implementation of the plugin to
facilitate the file upload as mentioned above.
LOAD THE FILE FROM LOCALHOST OR ANY HOSTED PLATFORM
PROVIDE THE 3 files in js/ directory
- js/jquery.ui.widget.js
- js/jquery.iframe-transport.js
- js/jquery.fileupload.js
THANKS TO THIS STACKOVERFLOW THREAD:
https://stackoverflow.com/q/17451629/1743124
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing jQuery File Upload</title>
<!-- BOOTSTRAP FOR STYLING -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- IONICONS FOR ICONS -->
<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- APP STYLES -->
<style type="text/css">
.uploaded-file {
background: linear-gradient(to right, lightblue 50%, transparent 50%);
background-size: 200% 100%;
background-position: right bottom;
transition: all 1s ease;
}
.uploaded-file.done a {
background-color: lightgreen;
}
.uploaded-file.done .badge {
display: inline-block;
}
</style>
</head>
<body class="p-3">
<form action="" enctype="multipart/form-data" class="need-validation" novalidate>
<div class="form-group">
<label for="attachments" class="font-weight-bold d-block">Attachments (optional)</label>
<input type="file" name="attachments" id="attachments" accept=".doc, .docx, .pdf, .rtf, .xls, .xlsx, .odt, .jpg, .jpeg, .jpe, .gif, .png, .bmp, .tiff, .tif">
<div id="file-upload-status" class="mt-2"></div> <!-- PLACEHOLDER TO DISPLAY UPLOAD PROGRESS -->
<p class="text-info font-italic small"><i class="ion-information-circled mr-1"></i> Maximum 5 attachments allowed. Maximum upload size: 500mb per file. Allowed file types are: jpg, gif, bmp, tiff, png, pdf, docx, doc, xls, xlsx, rtf, odt</p>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<!-- JAVASCRIPTS -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- jQuery File Upload: Standalone -->
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
var maximum_num_files = 5;
var maximum_file_size = 500000000; // 500mb in Decimal bytes.
var accepted_file_formats = 'jpg|jpeg|jpe|png|gif|bmp|docx|doc|xls|xlsx|pdf|odt|rtf';
var accepted_file_regex = new RegExp('(\.|\/)(' + accepted_file_formats + ')$', 'i');
// ------------------------------------------
// Attachments
// using jQuery File Upload.
// https://github.com/blueimp/jQuery-File-Upload/
//
// Known Issue:
// Default validation is not working.
// Worked with https://stackoverflow.com/a/17636961/1743124
// ------------------------------------------
var attachment_field = $('#attachments');
attachment_field.fileupload({
dataType: 'json',
url: '//jquery-file-upload.appspot.com/',
autoUpload: false,
// Following confirugrations din't work.
// See: https://stackoverflow.com/questions/17451629/maxfilesize-and-acceptfiletypes-in-blueimp-file-upload-plugin-do-not-work-why#comment54025049_20076562)
//
// disableValidation: false,
// limitConcurrentUploads: maximum_num_files,
// limitMultiFileUploads: maximum_num_files,
// maxFileSize: maximum_file_size,
// acceptFileTypes: accepted_file_regex,
add: function (e, data) {
var uploadErrors = [];
// Limit the number of files to be uploaded.
if ($('#file-upload-status .uploaded-file').length >= maximum_num_files) {
uploadErrors.push(`You cannot upload more than ${maximum_num_files} files`);
}
// Limit to specific types only.
if (data.files[0]['type'].length && !accepted_file_regex.test(data.files[0]['type'])) {
uploadErrors.push(`${data.files[0].name} is not an accepted file type`);
}
// Keep within the size limit.
if (data.files[0]['size'].length && data.files[0]['size'] > maximum_file_size) {
uploadErrors.push(`Filesize of ${data.files[0].name} is too big`);
}
if (uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.context = $('<div class="uploaded-file d-block mb-2 clearfix"></div>')
.append($('<button type="button" class="float-right btn js-delete-file delete" data-type="DELETE" data-url=""><i class="ion-close-circled" aria-hidden="true"></i> <span class="sr-only">Delete ' + data.files[0].name + '</span></button>'))
.append($('<a class="btn btn-block btn-link text-dark text-left" target="_blank" rel="noopener"></a>').text(data.files[0].name).append('<span class="badge badge-success badge-pill ml-2 text-uppercase"><i class="ion-android-checkmark-circle mr-1" aria-hidden="true"></i> Ready</span>'))
.appendTo(document.querySelector('#file-upload-status'));
data.submit();
}
},
progress: function (e, data) {
var progress = parseInt((data.loaded / data.total) * 100, 10);
data.context.css('background-position-x', 100 - progress + '%');
},
done: function (e, data) {
data.context
.addClass('done')
.find('a')
.prop('href', data.result.files[0].url);
data.context
.find('button')
.attr('data-url', data.result.files[0].url);
}
});
// Delete the Attachment.
$('body').on('click', '.js-delete-file', function(event) {
if (confirm('Are you sure you want to remove the attachment?')) {
var row = $(this).parent();
// $.get('/delete-file.php?id=' + row.attr('id'), function (data) {
row.slideUp('slow', function () {
row.remove();
});
// });
return false;
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment