我尝试使用Ajax和PHP单击按钮后上传文件并将其移动到文件夹。确实会成功返回true,但是上载的文件不会移动到目标文件夹。这是Ajax上传的片段
btnsubmit = $(".submit");
//the function for handling button click
btnsubmit.click(function(){
var file_data = $('#uploaded_img').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload_img_custom.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(php_script_response){
alert(php_script_response);
}
});
});
这是PHP文件
<?php
$upload_directory = "../uploads/Customized/";
if (isset($_FILES['uploaded_img']))
{
$uploadedFileName=$_FILES['uploaded_img']['name'];
$targetPath=time().$uploadedFileName; //time is concatenated to make filenames unique
if($uploadedFileName != '')
{
$targetPath=time().$uploadedFileName;
move_uploaded_file($uploadedFileName, $upload_directory."".$targetPath);
}
}
header('Location: customize.php?upload=success');
?>
HTML(仅重要部分)
<form method=POST id=customize-form action ="" enctype=multipart/form-data>
<div id=step3 class='options step'>
<section class=section-title>Image</section>
<div class=image-display><img id=image-disp src="" width=99 style="text-align:center" /></div> //div for displaying uploaded image
<section style="margin-bottom:10px">
<label class="paragraph-font2 full-width">Choose what you want on the top of your cake:</label>
</section>
<section style="margin-bottom:15px">
<input class="paragraph-font2 full-width" type=file name=uploaded_img id=uploaded_img accept="image/*">
</section>
</div>
<button type=submit class='btn btn-info action submit'><span class='glyphicon glyphicon-shopping-cart'></span> Add to cart</button>
</form>
我已经检查了上传限制。我要上传的文件只有170KB。我设置的上限为20M。“自定义”文件夹位于xampp htdocs中此项目的另一个文件夹内。
由于您将文件变量命名为“ file”(在JS中),因此您也应该在PHP代码中使用“ file”:
if (isset($_FILES['file']))
和
$uploadedFileName=$_FILES['file']['name'];
或者您更改JS部分:
form_data.append('uploaded_img', file_data);
并且您需要移动临时文件名,而不是原始文件名:
move_uploaded_file($_FILES['file']['tmp_name'], $upload_directory . $targetPath);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句