简体   繁体   English

使用 AJAX 和 PHP 上传文件

[英]Upload file using AJAX and PHP

I am trying to upload a file to a directory using AJAX and PHP.我正在尝试使用 AJAX 和 PHP 将文件上传到目录。 However I think there is an error with AJAX passing the file into PHP.但是我认为 AJAX 将文件传递到 PHP 时出错。

<form class="csvUpload" enctype="multipart/form-data">
    <input type="file" class="insertCsv" name="csvUpload"></input>
    <input type="submit" class="insertButton"></input>
</form>

AJAX:阿贾克斯:

$(".csvUpload .insertButton").click(function() {
    event.preventDefault();

    var file = $(".csvUpload .insertCsv").prop('files')[0];
    var data = new FormData();

    data.append('file', file);

    $.ajax({
        url: '/scripts/csvUpload.php', 
        type: 'POST', 
        dataType: 'json', 
        data: ({data}),
        processData: false,
        contentType: false,   
        success: function(data) {
            $(.output).text(data);
        }
    });
});

PHP: PHP:

$file = $_FILES['file']['tmp_name'];
$directory = $_SERVER['DOCUMENT_ROOT'] . '/imports/' . $_FILES['file']['name'];

if(move_uploded_file($file, $directory)) {
    echo('Success');
}
else {
    echo json_encode('Error');
}

I have tried various ways of passing the formdata, but everytime I get the 'Error' Output.我尝试了各种传递表单数据的方法,但每次我都得到“错误”输出。 How can I correctly pass the file and check that it is even being picked up?我怎样才能正确传递文件并检查它是否被拾取?

data: ({data}),

You are passing a simple object and telling jQuery not to process it.您正在传递一个简单的对象并告诉 jQuery 不要处理它。 It will get stringified and the data you end up posting will be "[object Object]" .它将被字符串化,您最终发布的数据将是"[object Object]"

You need to pass your FormData object.您需要传递您的 FormData 对象。 Only your FormData object.只有您的 FormData 对象。 And not wrap it in anything.不要用任何东西包裹它。

data: data,

Here I'm with solution, to upload image/file using Ajax .这里我有解决方案,使用Ajax上传图像/文件。 Follow the below code.按照下面的代码。

HTML: HTML:

<form class="csvUpload" enctype="multipart/form-data">
    <input type="file" class="insertCsv" name="csvUpload"></input>
    <input type="submit" class="insertButton"></input>
</form>

Jquery/Ajax:查询/阿贾克斯:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('.insertButton').on('click', function(e) { 
e.preventDefault(); 
var url = "/scripts/csvUpload.php";  
var file_data = $(".insertCsv").prop("files")[0]; 
var form_data = new FormData(); 
form_data.append("file", file_data); 
var dataString = 'file_data='+file_data+'&form_data='+form_data;    
form_data.append("data", dataString); 

$.ajax({
        url: "/demo_project/uploade/uploads.php",
        dataType: 'script',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(data){
            alert(data); 
        }
    }); 

});
</script>

Uploads.php:上传.php:

<?php 

define ('SITE_ROOT', realpath(dirname(__FILE__)));
echo SITE_ROOT;
if(isset($_REQUEST['data']) && $_REQUEST['data'] != '') { 
    if ($_FILES['file']['error'] > 0) { 
        echo 'Error: ' . $_FILES['file']['error'] . '<br>'; 
    } else { 
        move_uploaded_file($_FILES['file']['tmp_name'], SITE_ROOT.'/'. $_FILES['file']['name']); 
        echo "success";
    } 
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM