Skip to content

Instantly share code, notes, and snippets.

@taufik-nurrohman
Last active December 9, 2021 15:30
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 taufik-nurrohman/5981debd5aef0ac680bb40502100729b to your computer and use it in GitHub Desktop.
Save taufik-nurrohman/5981debd5aef0ac680bb40502100729b to your computer and use it in GitHub Desktop.
$(function() {
const caption = $('.figure-caption');
const figure = $('.figure');
const image = $('.figure-img');
const input = $(':file');
input.change(function() {
caption.text(this.files[0].name);
let data = new FormData(),
json, text = "",
xhr = new XMLHttpRequest();
data.append('imageToUpload', this.files[0]);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
json = JSON.parse(this.responseText);
text += '<div class="alert alert-info mt-4">';
text += json.messages + '<br>';
text += json.details.type + '<br>';
text += json.details.size + '<br>';
text += json.details.path.replace(/^(Path:\s*)(.*?)$/i, '$1<a href="$2" target="_blank">$2</a>');
text += '</div>';
// Display response text after the uploaded file
caption.after(text);
// Get the path
let path = json.details.path.replace('Path: ', "");
image.replaceWith('<img src="' + path + '" class="figure-img img-fluid rounded" alt="' + caption.text().replace(/\.[^/.]+$/, "") + '" onerror="this.onerror=null;this.src=\'https://via.placeholder.com/600x400\';">');
}
};
xhr.open('POST', '/stockx/dashboard/uploadImage', true);
xhr.send(data);
// Adding data attribute to change the button text after the chosen file
input.attr({"data-text": "Change Image", "value": "Change Image"});
// $('#field-1::before').css({'content': 'Change Image'});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment