【问题标题】:Image Upload in PHP using AJAX Jquery not working使用 AJAX Jquery 在 PHP 中上传图像不起作用
【发布时间】:2016-11-11 18:40:13
【问题描述】:

我有一个包含 4 个文本字段和一个图像文件的表单。我必须通过 AJAX 调用上传它。工作 2 天后......我已经成功了......但是有一个问题

<script type="text/javascript">
$(document).ready(function(){

// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
  //alert(files);
}


$("#myProfileForm").submit(function(event){
    event.preventDefault();
    document.getElementById("messageBlock").style.display = 'none';
    // Serialize the form data.
    var form = $('#myProfileForm');
    var formData = $(form).serialize();

    // Submit the form using AJAX.
$.ajax({
    type: 'POST',
    dataType: 'json',
    processData: false, 
    contentType: false, 
    url: $(form).attr('action')+'?'+files,
    data: formData
    alert(url);
}).done(function(response) {
    var formMessages = $('#form-messages');

    if(response.error){
        document.getElementById("messageBlock").style.display = 'block';
        $(formMessages).html(response.message);
    }else{
        document.getElementById("messageBlock").style.display = 'block';
        $(formMessages).html(response.message);
    }
})
}); 
});
</script>

我的 PHP 文件代码:

if (isset($_FILES['image_url'])){
$name       = $_FILES['image_url']['name'];  
$image_url = $name;
$temp_name  = $_FILES['image_url']['tmp_name'];  
if(isset($name)){
if(!empty($name)){      
    $location = 'uploads/';      
    if(move_uploaded_file($temp_name, $location.$name)){
    //echo 'File uploaded successfully';
            $image_url = UPLOADED_IMG_URL.''.$location.''.$name;
    }
}       
}  else {
$image_url = DEFAULT_IMAGE;
}
}else {
$image_url = '../../API/v1/uploads/default.PNG';
}

PHP 代码运行良好。问题在于 AJAX 调用。当我评论 //alert(url);

如果 (isset($_FILES['image_url'])) 返回 false,事情就会停止工作。不确定..是什么导致了问题。

【问题讨论】:

  • 对象应由key : value 对组成。你不能只放一个alert(url)

标签: php jquery ajax image


【解决方案1】:

serialize() 不适用于多部分数据,相反,您应该使用 Formdata() 方法。看看这个stack question;还从 $.ajax 中删除该警报;你不能那样做。

【讨论】:

  • 很好...那么我通过 var form = $('#myProfileForm'); 获得的其他输入数据呢? var formData = $(form).serialize();我也需要它们 + 文件数据
猜你喜欢
  • 2012-06-22
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多