我有一个名为uploads
的文件夹,以及名为upload.html
和upload.php
的文件。我的upload.html
看起来像这样(好吧,至少相关部分会这样做):
$(document).ready(function(){
$("#pictureUploadSubmit").submit(function(event) {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('fileToUpload', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
event.preventDefault();
});
});
我的upload.php
看起来像这样:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
现在,该文件似乎正在上传,但我认为它被上传到一个不正确的目录,因为当我尝试上传同一个文件两次时,它回显,Sorry, file already exists
并且当图像成功上传时,它回声"The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."
。但是,我的FireFTP中已存在的文件未显示在我的uploads
文件夹中。
我相信我已经允许适当的许可,即我允许读取,写入和执行我的上传文件夹。
所以我认为这是我target directory
的误导。我试着搜索上传的文件,我想我检查了所有目录,但我找不到它们。有人解决这个问题吗?
答案 0 :(得分:1)
您正在使用相关目录进行上传,
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
# ...
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
这会将文件移动到相对于此脚本运行位置的uploads目录。查看upload.php所在的目录,其中可能有一个上传目录与您的文件。
如果不是这种情况,我建议使用$target_dir
的绝对路径,这样您就可以确信知道最终文件的放置位置。