使用php脚本上传文件而不离开该页面

时间:2013-05-15 09:59:15

标签: javascript jquery ajax post

我正在尝试使用php脚本在html上传文件。

<html>
<body>
  <form id='importPfForm' enctype="multipart/form-data" action="http://localhost/js/upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form>
</body>
</html>

并且“upload.php”包含以下代码:

<?php
$upload_key = 'uploaded_file';
if (isset($_FILES[$upload_key])) {
    try {
        $error = $_FILES[$upload_key]['error'];
        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                throw new Exception('Exceeded upload_max_filesize');
            case UPLOAD_ERR_FORM_SIZE:
                throw new Exception('Exceeded MAX_FILE_SIZE');
            case UPLOAD_ERR_PARTIAL:
                throw new Exception('Incomplete file uploaded');
            case UPLOAD_ERR_NO_FILE:
                throw new Exception('No file uploaded');
            case UPLOAD_ERR_NO_TMP_DIR:
                throw new Exception('No tmp directory');
            case UPLOAD_ERR_CANT_WRITE:
                throw new Exception('Can\'t write data');
            case UPLOAD_ERR_EXTENSION:
                throw new Exception('Extension error');
        }
        $finfo    = new finfo(FILEINFO_MIME);
        $name     = $_FILES[$upload_key]['name'];
        $tmp_name = $_FILES[$upload_key]['tmp_name'];
        $size     = $_FILES[$upload_key]['size'];
        if ($size > 350000)
            throw new Exception('Exceeded 350KB limit');
        if (!is_uploaded_file($tmp_name))
            throw new Exception('Not an uploaded file');
        $type = $finfo->file($tmp_name);
        if ($type === false)
            throw new Exception('Failed to get MimeType');
        if ($type !== 'text/plain; charset=us-ascii')
            throw new Exception('Only csv available');
        $new_name = dirname(__FILE__).'/upload/'.$name;
    echo  $new_name;
        if (is_file($new_name))
            throw new Exception("The file {$new_name} already exists");
        if (!move_uploaded_file($tmp_name,$new_name))
            throw new Exception('Failed to move uploaded file');
        echo "File successfully uploaded as {$new_name}";
    } catch (Exception $e) {
        echo 'Error: '.$e->getMessage();
    }
}
?>

但是这种方法会打开一个新的网页。我想在不离开网页的情况下执行该功能,我需要在html页面中使用变量$new_name。我需要在html页面中执行哪些修改?我很确定这可以通过某种ajax请求来实现。但我不知道我在说什么。我对ajax或javascript并不大,但这是我经常使用的一个函数,我想学习它是如何工作的,所以我可以在现在和将来需要的时候实现它。

1 个答案:

答案 0 :(得分:1)

这里有两种选择。您可以使用以下代码作为表单的操作,然后将php放在同一个文件中。

<?php echo $_SERVER['PHP_SELF']; ?>

或者

header("Location: upload.html?new_name=value_of_new_name");

在upload.php中成功,然后在upload.html中,您可以使用$_GET['new_name']来检索$new_name的值