doulin6448 2014-09-23 18:18
浏览 74
已采纳

Ajax图像上传通知

i think i sleep already, cant find my mistake. Thanks for your advance for this short post and for your help.

My Javascript

$("#avatarImage").change(function() {
    $("#avatar").html('<img src="assets/images/loader.gif" alt="">');
    $.post( 'ajax/avatarUpload.php', function( data ) {
        alert(data);
    });
});

My Form

<form enctype="multipart/form-data" method="post" action="ajax/avatarUpload.php" id="avatarUpload">
    <span class="btn btn-teal btn-file btn-sm"><span class="fileupload-new"><i class="fa fa-pencil"></i></span><span class="fileupload-exists"><i class="fa fa-pencil"></i></span>
        <input type="file" name="avatar" id="avatarImage">
    </span>
</form>

My PHP Code

$file_up_size = $_FILES['avatar']['size'];
$file_name = md5(uniqid(rand(), true));
$add = '../assets/images/avatars/' . $file_name;

if(!move_uploaded_file($_FILES['avatar']['tmp_name'], $add)){
    echo 'FEHLER';  
} else {
    //database crap
}

My Error(s)

Notice:  Undefined index: avatar in ...

Thanks for your help, i am blind this evening.

  • 写回答

1条回答 默认 最新

  • douhui9192 2014-09-23 18:33
    关注

    Your $.post() is posting to the form but it is not supplying any data to that form. This is causing undefined index: avatar because your post doesn't include an index of avatar within the files array. To resolve this, pass along the image in your POST by constructing a FormData object. Further, the ajax wrapper $.post() doesn't allow you to set certain options, and therefore we need to unwrap it and use $.ajax() instead.

    $("#avatarImage").change(function() {
        $("#avatar").html('<img src="assets/images/loader.gif" alt="">');
        var fd = new FormData()
        fd.append('avatar', $('#avatarImage')[0].files[0]);
    
        $.ajax({
            url: 'ajax/avatarUpload.php',
            type: 'POST',
            data: fd,
            contentType: false,
            processData: false,
            success: function(data){
                console.log(data);
            }
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法