javascript - How do I check if a FormData file is empty? -


i'm creating ajax form includes option either specify background color or upload background image. goal bgcolor field ignored if file has been specified bgimg field.

<label>color: <input type="color" name="bgcolor" value="#000000"></label><br> <label>image: <input type="file" name="bgimg" accept="image/png"></label><br> 

i figured easiest way collect form data is, of course, using formdata api:

var fd = new formdata(document.getelementbyid('myform')); 

the problem is, don't know how check formdata object whether or not file has been selected. whether or not file input empty, fd.has('bgimg') returns true because field present--okay, that's sensible.

but although fd.get('bgimg') works fine if file has been specified, , can verify positive case, when file input empty same line straight crashes browser! (i've checked in firefox, happens consistently whether in actual script or browser console.) unfortunately "check whether there's file" operation recognizable undecidable useless. how supposed figure out if bgimg field empty?

i realize can check form's elements['bgimg'].files object, formdata api there, , it's neater, , would easier if weren't apparently fatally borked! missing something? if somehow wrong way use putatively convenient formdata object, hell supposed doing instead? checking files collection solution?

edit: further investigation reveals api has pretty poor support in browsers other firefox, checking element.files better solution. i'm still baffled why crashing browser in firefox, though. if answer on front not shortly forthcoming, i'll submit own answer.

this behavior of formdata api in firefox seems may bug, unfortunately. however, given rather minimal support formdata methods across browsers, better solution check form elements anyway:

var formfields = document.getelementbyid('mandelform').elements; console.log(formfields['bgimg'].files.length > 0); // true if file selected 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -