Created
October 1, 2013 07:15
-
-
Save BenjaminAdams/6774888 to your computer and use it in GitHub Desktop.
Upload image and/or a file with Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uploadImg: function(file, imgPreview, imgUrl) { | |
var self = this | |
console.log('file=', file) | |
imgPreview.html('<i class="icon-spinner icon-spin"></i>') | |
imgUrl.val('') | |
reader = new FileReader(); | |
reader.onload = (function(tFile) { | |
return function(evt, response) { | |
var xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange = function(ev) { | |
if (xhr.readyState == 4 && xhr.status == 200) { | |
if (xhr.responseText.indexOf('ERROR') !== -1) { | |
// $('#picPreview').html(' '); | |
imgPreview.html("<div class='alert'><button type='button' class='close' data-dismiss='alert'>×</button>" + xhr.responseText + "</div>"); | |
} else { | |
// $("#settingsErrors").html(" "); | |
console.log('evt=', evt) | |
console.log('xhr', xhr) | |
imgUrl.val(xhr.responseText) | |
imgPreview.html('<img src="' + evt.target.result + '" /> '); | |
// $('.usrProfilePicHolder').attr('src', evt.target.result); | |
// $('#settingsModal').modal('hide'); | |
} | |
} else if (xhr.readyState == 4 && xhr.status == 413) { | |
imgPreview.html("<div class='alert'><button type='button' class='close' data-dismiss='alert'>×</button>File size too big!</div>"); | |
} else if (xhr.readyState == 4 && xhr.status > 210) { | |
imgPreview.html("<div class='alert'><button type='button' class='close' data-dismiss='alert'>×</button>Error uploading file, try again :(</div>"); | |
} | |
}; | |
xhr.open('POST', '/uploadImg', true); | |
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
var data = '&type=' + file.type + '&file=' + encodeURIComponent(evt.target.result); | |
xhr.send(data); | |
// $("#settingsErrors").html("<div style='font-size:35px;color:white;'> <i class='icon-spinner icon-spin'> </i> </div> "); | |
}; | |
}(file)); | |
reader.readAsDataURL(file); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var file = $('.fileInput').get(0).files[0]; | |
if (!file) { | |
$(.error').html("Unable to upload image").show() | |
return; | |
} | |
var imgPreview = $('.imgPrev') | |
var imgUrl = $('.imgUrl') | |
this.uploadImg(file, imgPreview, imgUrl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment