image upload and crop client side including on old browsers - javascript

I am looking for some sort of image uploader and cropper that works mainly client side before it saves to the server.
I have tried a few things but have the issue that most of it is html5 based and I can't seem to find some sort of flash based uploader for the older browsers.
I got slightly lost with the jquery file uploader which I know can be used in the older browsers and the still need to work on a cropping function (but that looks like it will be mostly server side which would be a last resort).
I have also used http://www.script-tutorials.com/html5-image-uploader-with-jcrop/ which sort of works it uploads but when I want to test the crop function it keeps opening up the upload.php file. I will put the code below here :
<!DOCTYPE html >
<html>
<head>
<title>test image uploader</title>
<!--Stylesheets-->
<link href="css/colorbox.css" rel="stylesheet"/>
<link href="css/jquery.Jcrop.min.css" rel="stylesheet"/>
<!-- scripts-->
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.Jcrop.min.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
</head>
<body >
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm();">
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<h2>Please select image file</h2>
<div>
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler();"/>
</div>
<div class="error"></div>
<div class="step2">
<h2>Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label><input type="text" id="filesize" name="filesize" />
<label>Type</label><input type="text" id="filetype" name="filetype" />
<label>Image dimension</label><input type="text" id="filedim" name="filedim" />
<label>W</label><input type="text" id="w" name="w" />
<label>H</label><input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
</body>
<script type="text/javascript">
// convert bytes into friendly format
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
// check for selected crop region
function checkForm() {
if (parseInt($('#w').val())) return true;
$('.error').html('Please select a crop region and then press Upload').show();
return false;
};
// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#w').val(e.w);
$('#h').val(e.h);
};
// clear info by cropping (onRelease event handler)
function clearInfo() {
$('.info #w').val('');
$('.info #h').val('');
};
function fileSelectHandler() {
// get selected file
var oFile = $('#image_file')[0].files[0];
// hide all errors
$('.error').hide();
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (!rFilter.test(oFile.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').show();
return;
}
// check for file size
if (oFile.size > 250 * 1024) {
$('.error').html('You have selected too big file, please select a one smaller image file').show();
return;
}
// preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function (e) {
// e.target.result contains the DataURL which we can use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // onload event handler
// display step 2
$('.step2').fadeIn(500);
// display some basic image info
var sResultFileSize = bytesToSize(oFile.size);
$('#filesize').val(sResultFileSize);
$('#filetype').val(oFile.type);
$('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
// Create variables (in this scope) to hold the Jcrop API and image size
var jcrop_api, boundx, boundy;
// destroy Jcrop if it is existed
if (typeof jcrop_api != 'undefined')
jcrop_api.destroy();
// initialize Jcrop
$('#preview').Jcrop({
minSize: [100, 100], // min crop size
boxWidth:600,
aspectRatio: 9/6, // keep aspect ratio 1:1
bgFade: true, // use fade effect
bgOpacity: .4, // fade opacity
onChange: updateInfo,
onSelect: updateInfo,
onRelease: clearInfo
}, function () {
// use the Jcrop API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the Jcrop API in the jcrop_api variable
jcrop_api = this;
});
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
</script>
</html>
here is the upload.php code :
<?php
/**
*
* HTML5 Image uploader with Jcrop
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Script Tutorials
* http://www.script-tutorials.com/
*/
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$iWidth = $iHeight = 200; // desired image result dimensions
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'cache/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
/*case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;*/
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
The other problem with it is I have no fall back option for the older browsers mainly IE8 and 9 because of it only being html5 based.
can anyone please help with any idea's please.

Related

How to resize an image on preview (no database)

I have script to preview input type=file (image), and generate it into pdf.
There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.
So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.
Please help how to resize it on my script.
Script:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
//preview.src = reader.result;
$('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
HTML:
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/magang/front.css">
</head>
<body>
<div class="corpname" contenteditable>RUMAH SAKIT HARUM</div>
<div class="logosisma"><img src="https://sismadigroup.com/idcard/images/background/logo-id-card.png" width="219" height="70" /></div>
<div class="logo">
<!--<img src="resize/resize.php?src=https://sismadigroup.com/idcard/templates/images/avatar/3.jpg&scale=10&q=100">-->
<img src="https://sismadigroup.com/idcard/templates/images/avatar/3.jpg" width="200" height="240" />
</div>
<div class="name highlight" contenteditable>Maesyaroh</div>
<div class="position" contenteditable>Siswa Magang</div>
<div class="nik" contenteditable>SM-0035</div>
<div class="BBP">BENAR BAIK PANTAS</div>
<div class="BBPPoint" style="left:135px;"> . </div>
<div class="BBPPoint" style="left:203px;"> . </div>
</body>
</html>
Edit: PHP for PDF generation:
$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');
Since you are using PHP to generate the PDF you can resize the image with PHP before using it with mPDF. I don't see in your code how you load the image, so I suppose that you use the Image() function for loading the image from a file (in this example $fileName is the name of the input image, replace it with the variable that you use in your code):
// $fileName is the name of the input image
list($width,$height)=getimagesize($fileName); // size of input image
$tempFileName=tempnam(sys_get_temp_dir(),"img").".png";
$newWidth=200;
$newHeight=240;
$image=imagecreatefrompng($fileName); // load the input image
$newImage=imagecreatetruecolor($newWidth,$newHeight); //create an empty image
imagecopyresampled($newImage,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($newImage,$tempFileName,9); // saving the new image to disk
// here you create the PDF using the image saved in $tempFileName
unlink($tempFileName); // and finally we delete the temporal file
I solved the same problem on front-end, before uploading file. You can visit a link!
import imageSqResizer from './image-square-resizer.js'
let resizer = new imageSqResizer(
'image-input',
300,
(dataUrl) =>
document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);
//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;

creating an image uploader with preview in php and javascript

my code does not seem to be able to pull the image from my desktop for a preview. i don't know what. All it was does, is show me a broken image. Here is the code.
javascript
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg|\.png|\.gif/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg or png");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<img src="" width="10%" border="0" />';
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
HTML
<!-- iframe used for ajax file upload-->
<!-- debug: change it to style="display:block" -->
<iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
<!-- iframe used for ajax file upload-->
<form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<span>Upload Picture :</span>
<input type="file" name="picture" onclick="preview()" id="picture" onchange="return ajaxFileUpload(this);" />
<span id="picture_error"></span>
<div id="picture_preview"></div>
</div>
</form>
Something like this should work:
Javascript
var input = document.getElementById('image_uploader');
var uploadedImage = document.getElementById('uploaded_image');
input.addEventListener('change', onImageInput);
function onImageInput()
{
var imageFile = input.files[0];
var reader = new FileReader();
reader.addEventListener('loadend', onReaderComplete);
reader.readAsDataURL(imageFile);
}
function onReaderComplete(e)
{
uploadedImage.src = e.target.result;
}
HTML
<input type="file" id="image_uploader"/>
<div id="picture_preview"><img id="uploaded_image"/></div>
After this, you can send the image data (src) to the server with AJAX or other stuff like that.

Javascript: Persist file upload between redirects

Since there were no answers to this question:
Resumable.js: Persist file uploading between redirects and browser restarts
I am working on a workaround to let users upload their files in a separate popup, while they browse other pages. This is how I am passing my file objects to the popup window:
index.html:
<ol id="chosenFilesList"></ol>
Select files
<br>
<br>
<br>
Upload
<script src="resumable.js"></script>
<script>
var fileArr = [];
function displaySelectedFiles() {
var fileList = '';
for (var i = 0; i < fileArr.length; i++)
if(fileArr[i])
fileList += '<li>' + fileArr[i].name + '</li><a style="cursor: pointer;" onclick="removeFile(' + fileArr[i] + ');">Remove</a>';
//localStorage.setItem('fileArr', fileArr);
document.getElementById('chosenFilesList').innerHTML = fileList;
}
var r = new Resumable({
target:'test.html'
});
r.assignBrowse(document.getElementById('browseButton'));
r.on('fileSuccess', function(file){
console.debug('fileSuccess',file);
});
r.on('fileProgress', function(file){
console.debug('fileProgress', file);
});
r.on('fileAdded', function(file, event){
//r.upload();
fileArr.push(file.file);
displaySelectedFiles();
console.debug('fileAdded', event);
});
r.on('filesAdded', function(array){
//r.upload();
displaySelectedFiles();
console.debug('filesAdded', array);
});
r.on('fileRetry', function(file){
console.debug(file);
});
r.on('fileError', function(file, message){
console.debug('fileError', file, message);
});
r.on('uploadStart', function(){
console.debug('uploadStart');
});
r.on('complete', function(){
console.debug('complete');
});
r.on('progress', function(){
console.debug('progress');
});
r.on('error', function(message, file){
console.debug('error', message, file);
});
r.on('pause', function(){
console.debug('pause');
});
r.on('cancel', function(){
console.debug('cancel');
});
var popupWindow;
var addFiles = function() {
for (var i = 0; i < fileArr.length; i++) {
if(fileArr[i])
popupWindow.r.addFile(fileArr[i]);
}
//popupWindow.startUpload();
window.location.reload();
setTimeout('popupWindow.focus()', 1);
};
document.getElementById('uploadButton').addEventListener('click', function(evt) {
popupWindow = window.windowPop('', 900, 500);
if(popupWindow.location.href.indexOf('test.html') === -1) {
popupWindow.location.href = 'test.html';
setTimeout(function(){
popupWindow.onload = addFiles;
addFiles();
}, 300);
} else {
addFiles();
}
});
function windowPop(url, width, height) {
var leftPosition, topPosition;
//Allow for borders.
leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
//Allow for title and status bars.
topPosition = (window.screen.height / 2) - ((height / 2) + 50);
//Open the window.
return window.open(url, "Window2", "status=no,height=" + height + ",width=" + width + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
}
</script>
test.html:
<!DOCTYPE html>
<html>
<head>
<title>Resumable.js - Multiple simultaneous, stable and resumable uploads via the HTML5 File API</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="frame">
<h3>Demo</h3>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="resumable.js"></script>
<div class="resumable-error">
Your browser, unfortunately, is not supported by Resumable.js. The library requires support for the HTML5 File API along with file slicing.
</div>
<div class="resumable-drop" ondragenter="jQuery(this).addClass('resumable-dragover');" ondragend="jQuery(this).removeClass('resumable-dragover');" ondrop="jQuery(this).removeClass('resumable-dragover');">
Drop video files here to upload or <a class="resumable-browse"><u>select from your computer</u></a>
</div>
<div class="resumable-progress">
<table>
<tr>
<td width="100%"><div class="progress-container"><div class="progress-bar"></div></div></td>
<td class="progress-text" nowrap="nowrap"></td>
<td class="progress-pause" nowrap="nowrap">
<img src="resume.png" title="Resume upload" />
<img src="pause.png" title="Pause upload" />
</td>
</tr>
</table>
</div>
<ul class="resumable-list"></ul>
<script>
var r = new Resumable({
target:'/java-example/upload',
chunkSize:1*1024*1024,
simultaneousUploads:4,
testChunks: true,
throttleProgressCallbacks:1,
method: "octet"
});
// Resumable.js isn't supported, fall back on a different method
if(!r.support) {
$('.resumable-error').show();
} else {
// Show a place for dropping/selecting files
$('.resumable-drop').show();
r.assignDrop($('.resumable-drop')[0]);
r.assignBrowse($('.resumable-browse')[0]);
// Handle file add event
r.on('fileAdded', function(file){
// Show progress pabr
$('.resumable-progress, .resumable-list').show();
// Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
// Add the file to the list
$('.resumable-list').append('<li class="resumable-file-'+file.uniqueIdentifier+'">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-name').html(file.fileName);
// Actually start the upload
r.upload();
console.log(file);
});
r.on('pause', function(){
// Show resume, hide pause
$('.resumable-progress .progress-resume-link').show();
$('.resumable-progress .progress-pause-link').hide();
});
r.on('complete', function(){
// Hide pause/resume when the upload has completed
$('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
});
r.on('fileSuccess', function(file,message){
// Reflect that the file upload has completed
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(completed)');
});
r.on('fileError', function(file, message){
// Reflect that the file upload has resulted in error
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(file could not be uploaded: '+message+')');
});
r.on('fileProgress', function(file){
// Handle progress for both the file and the overall upload
$('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html(Math.floor(file.progress()*100) + '%');
$('.progress-bar').css({width:Math.floor(r.progress()*100) + '%'});
});
}
</script>
</div>
</body>
</html>
I just added / modified https://github.com/23/resumable.js/tree/master/samples/java sample HTML files.
I am just getting all the file objects from file selectors and uploading them in a separate window using resumable.js (I don't think library is important here). It works flawlessly on Chrome and Firefox.
The problem with this approach is, in IE 11- (as far as I tested), the file uploading stops as soon as user is redirected to another page.
Can anybody please tell me how can I make it work in all browsers (hopefully, using pure javascript)?
Also, it will be a lot helpful, if I can just persist an upload between browser restarts as well.

Show combined size of multiple uploaded files

I'm making an upload function with php, which works fine.
Only, because the maximum size in my php ini file is 32mb, I can't upload anything bigger than that. And that's fine with me.
BUT:
I want to prevent uploading when the combined size of all the files that are added to input-file, is over 32mb.
I found this script which alerts the file size after adding the files, which is a start:
$(function(){
$('#file').change(function(){
var file=this.files[0]
alert(file.size||file.fileSize)
})
})
But when testing I found out that it only returns the size of one file.
How can I alter this code to return the size of all the files that are added to the input field? Or is there another way to do this?
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Tutorial</title>
<link rel="stylesheet" type="text/css" href="css/tut.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<form action="tutorial.php" method="POST" enctype="multipart/form-data">
<!--<input type="file" name="myFile"><p>
<input type="submit" value="Upload">
<br/><br/>-->
<input type="file" name="files[]" multiple="multiple" id="file"/><p>
<input type="submit" value="Upload" id="submit" />
</form>
</div>
</body>
</html>
PHP code:
$file_dest = "photos/orig/";
$thumb_dest = "photos/thumbs/";
if(!empty($_FILES['files']['name'][0])){
$files = $_FILES['files'];
$uploaded = array();
$failed = array();
$allowedExt = array('png', 'jpg', 'gif');
foreach($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if(in_array($file_ext, $allowedExt)){
if($file_error == 0){
if($file_size <= 20000000){
$file_name_new = uniqid('', true)."_".$file_name;
$file_move = $file_dest.$file_name_new;
if(move_uploaded_file($file_tmp, $file_move)){
$uploaded[$position] = $file_dest;
}else{
$failed[$position] = "[{$file_name}] failed to upload.";
}
}else{
$failed[$position] = "[{$file_name}] is too large.";
}
}else{
$failed[$position] = "[P$file_name}] errored with code {$file_error}";
}
}else{
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}else{
echo "No files were added.";
}
Sidenote: The code's not finished yet, I still have to add security measures. Please ignore the lack thereof.
You'd do that by summing up the sizes
$(function(){
$('#file').on('change', function(){
var total = [].slice.call(this.files).map(function(x) {
return x.size || x.fileSize;
}).reduce(function(a, b) { return a + b; }, 0);
if ( total > 33554432 ) {
alert('Total size exceeds 32 mb');
}
});
});
FIDDLE
$(function(){
$('#file').change(function(){
var combinedSize = 0;
for(var i=0;i<this.files.length;i++) {
combinedSize += (this.files[i].size||this.files[i].fileSize);
}
alert(combinedSize);
})
})

Resize and upload files without AJAX

Edit
It seems that this is most likely not possible because the canvas and the file input are not compatible data types.
The way to do something similar is to send an AJAX request using a "data url". I will look into that in more detail. Since I didn't want to use AJAX I'll try to fake the workflow to be more like a normal submit, i.e. with a refresh at the end.
End edit
I want to resize and upload a file without AJAX, as this is how it is currently being done (without a resized image - taken from a phone/tablet) and it works well in terms of workflow.
Hence after doing a resize I want to be able to make the resized "image" the value of a field, if this is possible.
I am using this library http://gokercebeci.com/dev/canvasresize to do the resizing for me.
I tried setting the data variable in the callback to be the file1 input's value i.e.
$("#file1").val(data);
But this threw an error. I have removed it in the code below, since I was pretty sure that wasn't the way to go about it.
I've copied the entire HTML/JS file below (the "Image Uploading" content was an example of using AJAX to upload the image, I have commented it out because I don't want to do that).
<!DOCTYPE html>
<html>
<head>
<title>Resize and Upload Images</title>
<script type="text/javascript" src="/public/javascripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/public/javascripts/zepto.min.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.exif.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.canvasResize.js"></script>
<script type="text/javascript" src="/public/javascripts/binaryajax.js"></script>
<script type="text/javascript" src="/public/javascripts/canvasResize.js"></script>
<script type="text/javascript" src="/public/javascripts/exif.js"></script>
</head>
<body style="margin:48px;">
<div id="devcontainer">
<div id="area">
<h3>canvasResize</h3>
<div>
<form action="/upload" enctype="multipart/form-data" method="POST">
<input name="file1" type="file" id="file1"/>
<input name="file1" type="file"/>
<input name="data1" type="text"/>
<input name="data2" type="text"/>
</form>
<p><span></span></p>
<i></i>
</div>
<script>
$().ready(function() {
$('input[name=file1]').change(function(e) {
var file = e.target.files[0];
// RESET
$('#area p span').css('width', 0 + "%").html('');
$('#area img, #area canvas').remove();
$('#area i').html(JSON.stringify(e.target.files[0]).replace(/,/g, ", <br/>"));
// CANVAS RESIZING
canvasResize(file, {
width: 600,
height: 0,
crop: false,
quality: 80,
callback: function(data, width, height) {
// SHOW AS AN IMAGE
// =================================================
var img = new Image();
img.onload = function() {
$(this).css({
'margin': '10px auto',
'width': width,
'height': height
}).appendTo('#area div');
};
// /SHOW AS AN IMAGE
// =================================================
$(img).attr('src', data);
}
});
});
});
</script>
</div>
<div class="clearfix"></div>
</div>
</body>
</html>
<!--
// IMAGE UPLOADING
// =================================================
// Create a new formdata
var fd = new FormData();
// Add file data
var f = canvasResize('dataURLtoBlob', data);
f.name = file.name;
fd.append($('#area input').attr('name'), f);
var xhr = new XMLHttpRequest();
var loaded = Math.ceil((e.loaded / e.total) * 100);
$('#area p span').css({'width': loaded + "%"}).html(loaded + "%");
}
}, false);
// File uploaded
xhr.addEventListener("load", function(e)
{
var response = JSON.parse(e.target.responseText);
if (response.filename)
{
// Complete
$('#area p span').html('done');
$('#area b').html(response.filename);
$('<img>').attr({
'src': response.filename
}).appendTo($('#area div'));
}
}, false);
// Send data
xhr.send(fd);
}
-->
Create a callback function in the main window. Add an iFrame to the page that will handle file upload. Once your files have been uploaded call the call back function with the file names. Add the files to the canvas.

Categories