dynamically created HTML file input element doesn't post data
I have a form which is dynamically created using document.createElement. The components are created in the same way. The form is used to upload a file to a PHP script and when submitted loads the reponse in an iframe specified by the targe开发者_如何学编程t attribute of the form.
Unfortunately, the server receives a blank $_FILES array, and when I inspect the POST request I see that the file data wasn't included in the request. If I instead, on-the-fly, use the Google Chrome developer tools to edit the dynamically created form (in this process i just EDIT and then change absolutely none of the code), form submissions thereafter work perfectly, sending the relevant file data.
So this makes me realise that there is nothing wrong with the construction of my form in html, because it worked without changing anything. Which leads me to believe that the browser doesn't like me to dynamically create file input elements?
For completeness' sake, here is the dynamically generated form:
<form method="POST" action="includes/uploadPic.php"
enctype="multipart/form-data" target="fileResponse">
<input type="file" name="pic">
<input type="submit" value="Upload">
</form>
And print_r($_FILES)
gives an empty array on the server.
Can anyone explain this to me? My alternative is to statically create a hidden form in the document, and just append it to the relevant div when I need it, but I really dislike that kind of thing.
Below is the code that generates the form:
var form = document.createElement("form");
var fileUpload = document.createElement("input");
var uploadBut = document.createElement("input");
form.setAttribute("method", "POST");
form.setAttribute("action", "includes/uploadPic.php");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("target", "fileResponse");
fileUpload.setAttribute("type", "file");
fileUpload.setAttribute("name", "pic");
uploadBut.setAttribute ("type", "submit");
uploadBut.setAttribute ("value", "Upload");
form.appendChild(fileUpload);
form.appendChild(uploadBut);
dlgContent.appendChild(form);
try this:
var form = document.createElement("form");
var fileUpload = document.createElement("input");
var uploadBut = document.createElement("input");
form.method = "POST";
form.action = "includes/uploadPic.php";
form.enctype = "multipart/form-data";
form.target = "fileResponse"; /* I think you are trying to submit this from in an iframe */
fileUpload.type = "file";
fileUpload.name = "pic";
uploadBut.type = "submit";
uploadBut.value = "Upload";
form.appendChild(fileUpload);
form.appendChild(uploadBut);
dlgContent.appendChild(form);
If you put the form
tag within a div
tag, it does not post dynamically created elements to the server. However if you take it outside of the div
or table
tag, it works.
精彩评论