/******************************************************************** * PREVIEW, RESIZE, AND UPLOAD IMAGE VIA AJAX *********************************************************************/ // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ function previewImageUpload ($e) { var files = $e.target.files; if (files) { var imgContainerSelector = $e.target.getAttribute('data-img-preview-container'); var imgPreviewObj = URL.createObjectURL(files[0]); var $imgContainer = $(imgContainerSelector); $imgContainer.html(''); $imgContainer.find('img').attr('src', imgPreviewObj); } } // http://stackoverflow.com/a/5100158 function dataURItoBlob(dataURI) { // convert base64/URLEncoded data component to raw binary data held in a string var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = window.unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], {type:mimeString}); } function resizeWidth(file, max_width, callback) { max_width = max_width || 600; // Read image from file system and resize. var reader = new FileReader(); reader.onload = function(e) { var img = document.createElement('img'); img.src = e.target.result; // Specify new width and height. var width = img.width; var height = img.height; if (width > max_width) { height = parseInt(height * (max_width / width), 10); width = max_width; } // Create canvas which performs the re-sizing. var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; canvas.style.visibility = 'hidden'; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); var resizedFile = dataURItoBlob(canvas.toDataURL(file.type)); callback(resizedFile); }; reader.readAsDataURL(file); } function formatFilename(filename) { var extIndex = filename.lastIndexOf('.'); var basename = filename.slice(0, extIndex).replace(/\s+/g, '-'); var extension = filename.slice(extIndex); return basename + '-' + Date.now() + extension; } // Callback to ajax. It needs a special handler to upload images. var $inputImage = $form.find('.input-image-upload'); var imageFile = $inputImage[0].files[0]; var formattedFilename = (imageFile === undefined) ? self.model.get('logo_filename') : this.formatFilename(imageFile.name); resizeWidth(imageFile, 115, function(resizedFile) { var formData = new FormData(); formData.append('input-image-upload', resizedFile, formattedFilename); $.ajax({ url: '/api/brand-logo/', type: 'POST', data: formData, cache: false, processData: false, contentType: false, success: function(data, status) { console.log(data); } }); });