一个文件上传表单,它将变量传递给主html

时间:2011-10-29 19:59:19

标签: php jquery html ajax forms

已编辑以澄清问题。

我想要的地方:

  1. index.html中的文件上传表单。 (完成)
  2. 表单提交到PHP文件。 (完成)
  3. PHP文件将文件移动到正确的位置。 (完成)
  4. 重新加载index.html,并退出PHP。 (完成)
  5. index.html从PHP获取上传文件的位置,以便稍后使用。 (撤消)
  6. 我不知道,我如何将参数从PHP返回到index.html,或者问题是我不明白,PHP和HTML如何交换信息。

    所以问题是,这种功能是否可以用Ajax编写,所以我不需要“走出”我的index.html。

    我在html中有这个表单:

    <form method="post" enctype="multipart/form-data" action="uploader.php">
    <input type="file" name="uploadedfile"/>
    <input type="submit" name="submit" class="button" value="Submit"></button>
    </form>
    

    它调用的php看起来像这样:

    <?php
    $target_path = "uploads/";
    $target_path = $target_path . ( $_FILES["uploadedfile"]["name"]);
    if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_path)) {
    echo "Success!"
    } else{
    echo "There was an error uploading the file, please try again!";
    }
    header('Location: http://localhost/index.html');
    exit();
    ?>
    

    按提交后,文件正确上传到服务器。

1 个答案:

答案 0 :(得分:0)

您可以将index.html文件更改为php文件,以便它可以包含一些嵌入式PHP代码,然后执行以下操作。

的index.php

<form method="post" enctype="multipart/form-data" action="uploader.php">
<input type="file" name="uploadedfile"/>
<input type="submit" name="submit" class="button" value="Submit"></button>
</form>

<?php
if($_POST['target']){
    //Do stuff with the target
}
?>

uploader.php

<?php
$target_path = "uploads/";
$target_path = $target_path . ( $_FILES["uploadedfile"]["name"]);
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_path)) {
echo "Success!"
} else{
echo "There was an error uploading the file, please try again!";
}

//The following code POSTs data to index.php
$params = array('http' => array(
          'method' => 'POST',
          'content' => array('target' => $target_path)
        ));
$ctx = stream_context_create($params);
$fp = @fopen('index.php', 'rb', false, $ctx);
if (!$fp) {
    throw new Exception("Problem with index.php, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
?>

希望这会给你一些想法。