我有一个简单的PHP文件上传脚本,如此,
<?php
$path = 'uploads/';
$file_ext = array('jpg','png','gif','bmp','JPG');
$post_ext = end(explode('.',$_FILES['photo']['name']));
$photo_name = $_FILES['photo']['name'];
$photo_type = $_FILES['photo']['type'];
$photo_size = $_FILES['photo']['size'];
$photo_tmp = $_FILES['photo']['tmp_name'];
$photo_error= $_FILES['photo']['error'];
//move_uploaded_file($photo_tmp,"uploads/".$photo_name);
echo $photo_tmp;
if((($photo_type == 'image/jpeg') || ($photo_type == 'image/gif') ||
($photo_type == 'image/png') || ($photo_type == 'image/pjpeg')) &&
($photo_size < 2000000) && in_array($post_ext,$file_ext)) {
/* Understand in-Array !! */
if($photo_error > 0 ){
echo 'Error '.$photo_error;
exit;
}else{
echo $photo_name.' Uploaded !';
}
if(file_exists($path.$photo_name)){
echo 'There is '.$photo_name;
}else{
//new photo name and encryption
$new_name = explode('.',$photo_name);
$photo_name = 'erkan_'.md5($new_name[0]).'.'.$new_name[1];
//move to directory
if(move_uploaded_file($photo_tmp,$path.$photo_name)){
return $photo_name;
}
}
}
?>
表单代码:
<form action="fileupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="photo" id="fileBox">
<button type="submit">SUBMIT</button>
使用上面的脚本我的文件保存完好,但是当我在混合中添加一点ajax时,就像这样:
$(function(){
$('button[type="submit"]').on('click' , function(e){
e.preventDefault();
var formData = new FormData();
formData.append('photo', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'fileupload.php',
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
});
});
});
现在,当我上传图片时,图片未保存在我的上传文件夹中,为什么?
答案 0 :(得分:1)
您在type: "POST"
标记中遗漏了<script></script>
。
$(function(){
$('button[type="submit"]').on('click' , function(e){
e.preventDefault();
var formData = new FormData();
formData.append('photo', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: 'fileupload.php',
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
});
});
});
答案 1 :(得分:1)
你在ajax调用中有一些错误。
1 - 我为您的表单提供了ID
2 - 您没有从表单中获取值。
$(function(){
$('#submitBtn').on('click' , function(e){
e.preventDefault();
var form = $('form#myForm');
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url: formAction,
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
dataType: "json",
type : 'POST',
resetForm: true,
})
.done(function(data) {
//do something with the returned data
}
});
});
答案 2 :(得分:-2)
我认为您的文件名未正确设置。所以你的PHP无法获取该文件。试试这个
formData.append('photo', $('input[type=file]')[0].files[0],$('input[type=file]')[0].files[0].name);