javascript - multiple images upload using FormData and separate fields -
i want start upload images server before submit form can't nest forms use formdata()
the form contain title , 5 images captions , want start upload once choose image without click upload , , without submit main form , prevent submiting form until images uploaded
this part of code work first input only
$(document).ready(function(){ var counter = 2; $("#howaddbutton").click(function () { if(counter>25){ alert("error"); return false; } $('#file' counter +).change(function(){ var file_data = $('#file' counter +).prop('files')[0]; var form_data = new formdata(); form_data.append('file' counter +, file_data); $.ajax({ url: "upload.php", type: "post", data: form_data, contenttype: true, cache: false, processdata:true, success: function(data){ console.log(data); } }); }); var newtextboxdiv = $(document.createelement('div')) .attr("id", 'howtextboxdiv' + counter); newtextboxdiv.after().html( '<span id="content' + counter + '"><div class="btn btn-primary btn-file alert">'+ '<div id="response">'+'</div>'+ '<input type="file'+ counter +'" name="file'+ counter +'" id="file'+ counter +'">'+ '</div></span>'); }); });
..
<div id="howtextboxesgroup"> <div id="howtextboxdiv1"> <li><a> <input class="form-control input-md" placeholder="" required="required" type="textbox" name="how[0]" > </a></li> <span id="content"> <div class="btn btn-primary btn-file alert"> <div id="response"></div> <input type="file" name="file" id="file"> </div> </span> </div> </div> <button class="btn btn-success" name="plus" id="howaddbutton" type="button">+</button> <button class="btn btn-primary" name="minus" id="howremovebutton" type="button">-</button>
i think here problem
'<div id="response">'+'</div>'+ '<input type="file" name="file" id="file">'+
and how alert if file size large x or format not supported
you need make input file multiple able pick many files.
also need iterate on files when have chosen files, , listen on change event of input able read files.
i made single example, hope find helpful.
edit
here have working code expected, can create input dynamically.
$(document).ready(function(){ // let's encapsulate code prevent exposeness in window scope accessible console developer tools // soe let's make autoexec function, , let's declare our login inside // ($) code object injected @ bottom of function (function($){ // our counter images uploaded var imagesuploaded = []; // our limit reached var limittobereachedtoenabletheform = 0; // reference our btnsubmit var btnsubmit = $("#mybtnsender"); // reference our form var form = $("#myform"); // let's save reference each input file var picker = $(".file-picker"); var blockwrapper = $(".wrap-block"); var addblockbtn = $("#add-picker-block"); var blockid = "block-id-"; // let's listen picker (change) event each input file function onhandlefile(event) { // file var file = event.target.files; // file inside of collection files file = file[0]; var fileid = $(this).attr("id"); // let's make sure file image, need define format of images allow var allowimagestypes = ["image/jpg","image/gif", "image/png", "image/jpeg"]; var imagetype = file.type; // if current image type not supported, abort process , notify user if (allowimagestypes.indexof(imagetype) === -1) { var messageallowedtypes = allowimagestypes.join(", "); alert("error, support these types of images : " + messageallowedtypes); return false; } // if current type image allowed let's title, caption , let's upload image var currentpicker = $(this); var parentpickerblock = currentpicker.parent(".block-image-picker"); var title = parentpickerblock.find('.image-title'); title = title.length > 0 ? $.trim(title.val()) : ""; var caption = parentpickerblock.find('.image-caption'); caption = caption.length > 0 ? $.trim(caption.val()) : ""; uploadimage(title, caption, file, parentpickerblock, fileid); }; form.submit(function(){ // if imagesuploaded less limittobereachedtoenabletheform, there images upload , not allow submittion of form if (imagesuploaded.length < limittobereachedtoenabletheform) { return false; } alert("your form send :d"); return true; }); addblockbtn.on("click", addnewblock); function checktotalimagesuploaded(fileid) { if (fileid) { imagesuploaded.push(fileid); } // if 5 images uploaded enabled submit button checkuploadstoenablesubmitbutton(); } function checkuploadstoenablesubmitbutton() { if (imagesuploaded.length === limittobereachedtoenabletheform) { btnsubmit.removeattr("disabled"); } else { btnsubmit.attr("disabled", "disabled"); } } function removeimageuploadedcounterifexists(fileid) { var index = imagesuploaded.indexof(fileid) if (index > -1) { imagesuploaded.splice(index, 1); } } function addnewblock() { // create block inputs elements var blockimagepicker = $("<div class='block-image-picker'>"); var inputtitle = $("<input type='text' name='imagetitle[]' class='image-title' placeholder='your image title' />"); var inputfile = $("<input type='file' name='images[]' class='file-picker' />"); // generate timestamp of creation var fileid = new date() * 1; inputfile.attr("id", fileid); // put blockimagepicker blockimagepicker.append(inputtitle); blockimagepicker.append(inputfile); // add block wrapper blockwrapper.append(blockimagepicker); // increment our limit counter limittobereachedtoenabletheform++; // add data-id attribute blockimagepicker.attr("id", blockid + limittobereachedtoenabletheform); if (limittobereachedtoenabletheform > 1) { var removebtn = $("<button>remove</button>"); blockimagepicker.append(removebtn); removebtn.data("container-id", blockid + limittobereachedtoenabletheform); removebtn.on("click", onremoveblockpicker); } // add event listener file picker inputfile.on("change", onhandlefile); checkuploadstoenablesubmitbutton(); } function onremoveblockpicker(event) { event.preventdefault(); // input file remove eventlistener var filepickerreference = $(this).prev(); var fileid = filepickerreference.attr("id"); // remove event listener filepickerreference.off("change"); // block id current block var containerid = $(this).data("container-id"); var containerblock = $("#"+containerid); containerblock.remove(); limittobereachedtoenabletheform--; removeimageuploadedcounterifexists(fileid); checkuploadstoenablesubmitbutton(); } function uploadimage(title, caption, file, parent, fileid) { var formdata = new formdata(); formdata.append("title", title); formdata.append("caption", caption); formdata.append("image", file); var loader = $("<div>"); $.ajax({ url: 'http://my-url-endpoint-rest', data: formdata, type: 'post', contenttype: false, processdata: false, beforesend: function() { //beforesend image upload, let's show user happening loader.text("uploading " + file.name + " ..."); parent.append(loader); }, success: function(response) { // if image uploaded increment our counter imagesuploaded checktotalimagesuploaded(fileid); }, error: function(jqxhr, textstatus, errormessage) { // show error if wrong console.log("error", errormessage); // optional alert("error uploading image " + file.name); }, complete: function() { // remove loader, not matter if response wrong or loader.remove(); } }); } // create our first block when page loaded addnewblock(); })($); // ($) code above inject jquery object closure });
.block-image-picker { border: 1px solid blue; margin-bottom: 5px; padding: 5px; } .block-image-picker input { display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form id="myform"> <div class="file-pickers-wrapper"> <div class="wrap-block"> </div> <div class="controls"> <button id="add-picker-block"> add new field </button> </div> </div> <button type="submit" id="mybtnsender" disabled="disabled"> send data </button> </form>
Comments
Post a Comment