dongtiao0279 2018-08-28 10:41
浏览 70
已采纳

使用Ajax,Jquery的Fileupload

im relatively new to coding, but nevertheless have got a little problem. My main problem basically is that the file I have chosen to upload doesnt end up in the toimport folder on the Server, altough the function shows a success. Please help if you may know a solution to this problem.

The script from Upload_form.php :

<script>
// Wir registrieren einen EventHandler für unser Input-Element (#uploadFile)
// wenn es sich ändert
$('body').on('change', '#uploadFile', function() {
    var data = new FormData(); // das ist unser Daten-Objekt ...
    data.append('file', this.files[0]); // ... an die wir unsere Datei anhängen
    $.ajax({
        url: 'upload.php', // Wohin soll die Datei geschickt werden?
        data: data,          // Das ist unser Datenobjekt.
        type: 'POST',         // HTTP-Methode, hier: POST
        processData: false,
        contentType: false,
        // und wenn alles erfolgreich verlaufen ist, schreibe eine Meldung
        // in das Response-Div
        success: function() { $("#responses").append("Datei erfolgreich hochgeladen");
        }
    });
});
</script>

upload.php

$target_dir = "toimport/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Allow certain file formats
if($FileType != "xlsx" && $FileType != "xls" && $FileType != "csv"
    && $FileType != "gif" ) {
    echo "Sorry, only XLSX, XLS & CSV files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],     $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
    }
}
  • 写回答

1条回答 默认 最新

  • duanbo6871 2018-08-28 11:01
    关注
    1. You need to write jQuery in $(document).ready(function(){...}) or $(function(){...})
    2. enctype: 'multipart/form-data', to $.ajax
    3. $_FILES["file"] instead of $_FILES["fileToUpload"]

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
            crossorigin="anonymous"></script>
        <script>
            $(function () {
                $('body').on('change', '#uploadFile', function () {
                    console.log('asdfsadfa');
                    var file_data = $('#uploadFile').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: form_data,
                        contentType: false,
                        cache: false,
                        enctype: 'multipart/form-data',
                        processData: false,
                        success: function (data) {
                            console.log(data);
                            $("#responses").append("Datei erfolgreich hochgeladen");
                        }
                    });
                });
            })
        </script>
    </head>
    
    <body>
        <input type="file" id="uploadFile" />
        <div id="responses"></div>
    </body>
    
    </html>

    PHP Code:

    <?php
    
    $target_dir = "toimport/";
    
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $FileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    
    // Allow certain file formats
    if ($FileType != "xlsx" && $FileType != "xls" && $FileType != "csv"
        && $FileType != "gif") {
        echo "Sorry, only XLSX, XLS & CSV files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file ". basename($_FILES["file"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘