当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - AJAX, HTML5 Image previewer + removal before upload

问题描述:

I got an image preview working and uploading. My question is how can I make the code only upload whatever is in the preview area? ie. if I select images and remove them, they should not get uploaded upon submission.

I got it to work with jquery with a fake "upload" just to illustrate what I am after but not sure how to send only the images in the preview area to PHP.

If I can somehow get this dynamic list of the images from the preview area into an array, I will easily be able to upload them with PHP, the hard part is getting that list!

Here is a demo: http://jsfiddle.net/WCCM7/3/

var $fileUpload = $("#files"),

$list = $('#list'),

thumbsArray = [],

maxUpload = 5;

// READ FILE + CREATE IMAGE

function read( f ) {

return function( e ) {

var base64 = e.target.result;

var $img = $('<img/>', {

src: base64,

title: encodeURIComponent(f.name), //( escape() is deprecated! )

"class": "thumb"

});

var $thumbParent = $("<span/>",{html:$img, "class":"thumbParent"}).append('<span class="remove_thumb"/>');

thumbsArray.push(base64); // Push base64 image into array or whatever.

$list.append( $thumbParent );

};

}

// HANDLE FILE/S UPLOAD

function handleFileSelect( e ) {

e.preventDefault(); // Needed?

var files = e.target.files;

var len = files.length;

if(len>maxUpload || thumbsArray.length >= maxUpload){

return alert("Sorry you can upload only 5 images");

}

for (var i=0; i<len; i++) {

var f = files[i];

if (!f.type.match('image.*')) continue; // Only images allowed

var reader = new FileReader();

reader.onload = read(f); // Call read() function

reader.readAsDataURL(f);

}

}

$fileUpload.change(function( e ) {

handleFileSelect(e);

});

$list.on('click', '.remove_thumb', function () {

var $removeBtns = $('.remove_thumb'); // Get all of them in collection

var idx = $removeBtns.index(this ); // Exact Index-from-collection

$(this).closest('span.thumbParent').remove(); // Remove tumbnail parent

thumbsArray.splice(idx, 1); // Remove from array

});

// that's it. //////////////////////////////

// Let's test //////////////////////////////

$('#upload').click(function(){

var testImages = "";

for(var i=0; i<thumbsArray.length; i++){

testImages += "<img src='"+thumbsArray[i]+"'>";

}

$('#server').empty().append(testImages);

});

What I want essentially is this:

Please help me out! I have been stuck at this problem for a good month.

分享给朋友:
您可能感兴趣的文章:
随机阅读: