What I need is image upload within a form:
<input type="file" id="files" name="pics[]" multiple />
<br>
<output id="list"></output>
I have read a lot, including:
- Image resizing client-side with JavaScript before upload to the server
- Show an image preview before upload
- https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
Then come up with a solution, but it does not work:
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var img = document.createElement('img');
img.src = e.target.result;
var canvas = document.createElement('canvas');
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img class="thumb" src="',
dataurl,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
It won't do resize and won't do preview. However, multiple full size image upload still works.
EDIT: It does resize and does preview. But after I click submit the form, the full size original images are still uploaded.
Am I doing something wrong?