当我将文件上传到mysql时出现错误:“错误!文件未发送!”。
这是我的PHP代码,请查看它并告诉我代码中的错误。
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
<a href="list_files.php">See all files</a>
</p>
</body>
</html>
add_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file'] ['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
} else
{
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click <a href="index.html">here</a> to go back</p>';
?>
答案 0 :(得分:0)
您需要至少一个非文件表单字段才能正确提交表单。没有$ _POST数组中的数据,$ _FILES数组不会被设置。在文件输入字段上方添加隐藏的表单字段将修复它。
<input type="hidden" name="form_field">
<input type="file" name="uploaded_file"><br>
或者为提交按钮输入标记添加名称属性,如下所示:
<input type="submit" name="submit" value="Upload file">
在非工作演示中,您将看到,即使文件已上传,$ _FILES数组也是空的。
答案 1 :(得分:0)
如果您在执行
时获得HTTP Upload Disabled
if(ini_get('file_uploads') == 1){
echo 'HTTP Upload Enabled';
}
else {
echo 'HTTP Upload Disabled';
}
默认情况下,您的服务器上的 file_uploads
已关闭
如果您有权访问/并且可以修改您的php.ini
文件 -
file_uploads = 1
在.htaccess
文件中 -
php_value file_uploads 1
或者在你的php页面顶部
<?php
ini_set('file_uploads',1);
?>
请参阅http://www.php.net/manual/en/ini.core.php#ini.file-uploads