0

我的ajax成功:功能不起作用。当我成功上传文件时,它应该显示消息。但是,即使文件已成功上传,它也不显示消息。有人可以帮我解决这个问题吗?

这是我的代码;

            type: 'POST',
            url: 'upload.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $(".progress-bar").width('0%');
            },
            error:function(){
                $('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
            },
            success: function(resp){
                if(resp == 'ok'){
                    $('#uploadForm')[0].reset();
                    $('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
                    console.log('it works');
                }else if(resp == 'err'){
                    $('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
                }
            }

php代码:

$upload = 'err'; 
if(!empty($_FILES['file'])){ 
    $targetDir = "D:/MMHE4DFiles/"; 
    $allowTypes = array('avi'); 
    $path=$_POST['path'];
    $fileName = basename($_FILES['file']['name']); 
    $targetFilePath = $targetDir.$path.".avi";//$fileName; 

    // Check whether file type is valid 
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
    if(in_array($fileType, $allowTypes)){ 
        move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath);

        }

    if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){
        $upload = 'ok';
        echo $upload;
    }
}
4

1 回答 1

0

这行不通。

原因:您移动文件两次。但是在第一次移动之后它就消失了,所以第二次移动必须失败。

解决方案:

// Check whether file type is valid 
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 

    if(in_array($fileType, $allowTypes)){ 
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath) )
{
echo "ok";  
exit();} 

       }
echo "err";

(删除你的最后一段。)

于 2021-01-21T06:01:24.143 回答