我正在尝试使用 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();
}
}
?>
但是这种方法会打开一个新的网页。我想在不离开网页的情况下执行该功能,并且我需要 $new_name
在 html 页面中使用该变量。我需要在我的 html 页面中执行什么修改?我很确定这可以通过某种 ajax 请求来实现。但我不知道我在说什么。我对 ajax 或 javascript 不是很感兴趣,但这是我经常使用的一个函数,我想了解它是如何工作的,这样我就可以在现在和将来需要时实现它。