所以我有了这个文件index.php,它提供了一个上传图像的表单。
<!DOCTYPE html>
<html>
<head>
<title>Unnamed</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Include styles -->
<link href = "bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href = "css/style.css" rel="stylesheet">
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<!-- Include form plugin -->
<script src="http://malsup.github.com/jquery.form.js"></script>
<!-- Javascript -->
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#insert_movie').ajaxForm(function() {
$('#message').load('upload_file.php');
});
});
</script>
</head>
<body>
<!-- Message banner -->
<div id='message'></div>
<!-- Insert a movie into the database -->
<h1>Add a new movie to the list</h1>
<form id="insert_movie" 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>
</body>
</html>
注意:你们可能不熟悉,但我使用jQuery插件来轻松实现AJAX。 您可能需要查看此link
我通过upload_file.php评估此表单:
<?php
error_reporting(E_ALL);
//Upload the image
$allow = array("jpg", "jpeg", "gif", "png");
$todir = 'images/';
if(isset($_POST['submit'])){
if ( $_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
$info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file
if ( in_array( end($info), $allow) ) // is this file allowed
{
if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
{
echo "Great";
}
}
else
{
// error this file ext is not allowed
echo 'Choose another file extension';
}
}
}
echo "this works";
?>
所以问题是在“这个工作”旁边的任何东西都不会在标签中呈现。然而,上传工作完美无缺。
感谢所有帮助!
编辑:所以当我忘记ajaxing并简单地重定向到upload_file.php时,一切都变得非常精细......
答案 0 :(得分:2)
问题是您的表单是通过ajaxForm发送到upload_file.php的,并且一切都应该在此调用中正常工作,返回预期的字符串。使用此服务器响应,您的回调函数被调用,在这里您再次调用upload_file.php而不使用任何参数,并将结果呈现在div中,即只有&#34;这适用于&#34; 。您应该使用如下插件:
$('#insert_movie').ajaxForm({
success: function(response) {
$('#message').html(response);
}});
答案 1 :(得分:0)
可能你不需要使用!! $ _ FILES [&#39; file&#39;] [&#39; tmp_name&#39;]更好地写这个
if ($_FILES['file']['tmp_name'])
但更好的是你应该学习如何调试你的代码,这是最简单的方法:
if(isset($_POST['submit'])){
var_dump($_FILES['file']['tmp_name']);
if ( !!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
$info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file
var_dump($info);
if ( in_array( end($info), $allow) ) // is this file allowed
{
var_dump($todir . basename($_FILES['file']['name']));
if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
{
echo "Great";
}
}
else
{
// error this file ext is not allowed
echo 'Choose another file extension';
}
}
}