使用表单文本输入类型上传文件

时间:2014-02-23 16:17:20

标签: php html forms

目前我正在使用type="file"上传文件。但我的用例是从文本框本身上传给定的完整文件路径。

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

在提交表单页面中:

<?php move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; ?>

我想在文本框中指定文件路径,从那里我想上传图片。我怎么能完成它?

2 个答案:

答案 0 :(得分:2)

据我所知,您无法从客户端的计算机上传带文本框的文件。否则,从客户端窃取任何文件将非常容易,因为文本框可以使用JavaScript进行编辑。我希望我能正确理解你的问题。

编辑:您的意思是从您的计算机上传,还是从网址上传?第二个可以完成。

答案 1 :(得分:-1)

试试这个:

<?php

function h($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

if (
    isset($_POST['path'], $_FILES['upfile']['error']) &&
    is_int($_FILES['upfile']['error']) &&
    is_string($_POST['path'])
) {

    try {

        $deep = 0;
        foreach (explode('/', $_POST['path']) as $i => $hierarchy) {
            if ($deep > 9) {
                throw new RuntimeException('Hierarchy is too deep');
            }
            if ($hierarchy === '') {
                if ($_POST['path'] !== '' && $i === 0) { 
                    throw new RuntimeException('Absolute path is not allowed');
                }
                continue;
            }
            if ($hierarchy === '.') {
                continue;
            }
            if (!preg_match('/\A(?!\.)[\w.-]++(?<!\.)\z/', $hierarchy)) {
                throw new RuntimeException('Invalid directory name: ' . h($hierarchy));
            }
            if (!is_dir($hierarchy)) {
                if (!mkdir($hierarchy)) {
                    throw new RuntimeException('Failed to create directory: ' . h($hierarchy));
                }
                $msgs[] = 'Created directory "' . h($hierarchy) . '"';
                chmod($hierarchy, 0777);
            }
            chdir($hierarchy);
            ++$deep;
        }
        switch ($_FILES['upfile']['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new RuntimeException('File is not choosed');
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                throw new RuntimeException('File is too large');
            default:
                throw new RuntimeException('Unknown error occurred');
        }
        if ($_FILES['upfile']['size'] > 1000000) {
            throw new RuntimeException('File is too large');
        }
        if (!$info = getimagesize($_FILES['upfile']['tmp_name'])) {
            throw new RuntimeException('Invalid image file');
        }
        if (false === array_search(
            $info['mime'],
            array(
                'jpg' => 'image/jpeg',
                'png' => 'image/png',
                'gif' => 'image/gif',
            ),
            true
        )) {
            throw new RuntimeException('Unsupported image format');
        }
        if (!preg_match('/\A(?!\.)[\w.-]++(?<!\.)\z/', $_FILES['upfile']['name'])) {
            throw new RuntimeException('Invalid filename: ' . h($_FILES['upfile']['name']));
        }
        if (!move_uploaded_file(
            $_FILES['upfile']['tmp_name'],
            $_FILES['upfile']['name']
        )) {
            throw new RuntimeException('Failed to save uploaded file');
        }

        $msgs[] = 
            'Uploaded successfully: ' .
            ($_POST['path'] === '' ? '.' : $_POST['path']) .
            '/' .
            $_FILES['upfile']['name']
        ;

    } catch (RuntimeException $e) {

        $msgs[] = $e->getMessage();

    }

}

header('Content-Type: text/html; charset=utf-8');

?>
<!DOCTYPE html>
<html>
<head>
  <title>Hierarchical Image Uploading</title>
</head>
<body>
<?php if (isset($msgs)): ?>
  <ul>
<?php foreach ($msgs as $msg): ?> 
    <li><?=$msg?></li>
<?php endforeach; ?>
  </ul>
<?php endif; ?>
  <form enctype="multipart/form-data" method="post" action="">
    <fieldset>
      <legend>Select file (Directory name and filename must match <strong>'/(?!\A\.*+\z)\A(?!\.)[\w.-]++(?&lt;!\.)\z/'</strong>)</legend>
      Directory path: <input type="text" name="path" value=""><br />
      Filename(JPEG, PNG, GIF): <input type="file" name="upfile"><br />
      <input type="submit" value="Upload">
    </fieldset>
  </form>
</body>
</html>