Skip to content

Instantly share code, notes, and snippets.

@pste
Created July 14, 2017 12:57
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 pste/491a35b2e732ad0223714108b249a7cc to your computer and use it in GitHub Desktop.
Save pste/491a35b2e732ad0223714108b249a7cc to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<button id="uploadbtn">Click me to upload a file ...</button>
<form id="uploadform" action="sendfile" method="post" enctype="multipart/form-data" style="display:none">
<input id="uploadfile" type="file" name="file1" >
</form>
<script>
// when clicked, my button trigger the "browse file" dialog on the html file input
$('#uploadbtn').on('click', function() {
$('#uploadfile').click();
});
// when a file is chosen it triggers the form submit
$('#uploadfile').change(function() {
$('#uploadform').submit(); // do the real trigger
});
// hook a custom handler to the form submit, BLOCKING the submit method and POSTing the request
$('#uploadform').submit(function(event) {
var $form = $(this);
var formData = new FormData($form[0]); // needed in "multipart/form-data"
$.ajax({
url: $('#uploadform').attr('action'), // or another URL
type: 'POST',
data : formData, // send the form
cache: false,
contentType: false, // needed in "multipart/form-data"
processData: false, // needed in "multipart/form-data"
beforeSend: function () {
console.log('Uploading...');
},
success: function(data) {
console.log(data); // hey! I can read the server response! =)
console.log('Upload complete!');
}
});
event.preventDefault(); // do NOT submit
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment