user2961797
user2961797

Reputation: 29

Upload file with IFRAME, the file don't get to the server

Following my code:

HTML:

<form id="test" action="javascript:test()" method="post">
<input name="image" type="file" /> 
<input type="submit" value="Submit" />
</form>

JS:

function test(){
   iframe = document.createElement("IFRAME");  
   iframe.name = "iframe_upload";
   iframe.src="test.php";
   document.body.appendChild(iframe);
   document.getElementById("test").target = "iframe_upload";
}

PHP:

<?php
  if (isset($_FILES["image"])){
     echo 'exist';
     exit();
  }
?>

Where is the error? I'm sure the problem is in javascript, it would be easy to take off without the javascript dynamically create the iframe, but I must use javascript.

Upvotes: 0

Views: 648

Answers (1)

Matt Indeedhat Holmes
Matt Indeedhat Holmes

Reputation: 725

there are a couple of problems with that but nothing major,

firstly in order to post files you need to add enctype="multipart/form-data"to your form

seccondly the action of the form should be the file you are posting to (the iframe source) and the javascript should be run from onsubmit

finally you need to give the iframe an id for cross browser support

i end up with this

JS:

function test(){
     iframe = document.createElement("IFRAME");  
     iframe.name = "iframe_upload";
     iframe.id = "iframe_upload"; //some browsers target by id not name
     document.body.appendChild(iframe);
     document.getElementById("test").target = "iframe_upload";
  }

HTML:

<form id="test"   method="post" target="iframe_upload" enctype="multipart/form-data" onsubmit="javascript:test()" action="test.php">
<input name="image" type="file" /> 
<input type="submit" value="Submit" />
</form>

PHP:

<?php
  print_r($_FILES);
?>

Upvotes: 1

Related Questions