doucigua0278 2019-04-08 02:16
浏览 51

使用Ajax和PHP的文件阵列上传未通过.php文件

I'm Sending an Array a Files from a Form To a .php File, and it just takes all the other fields from the form but is not actually taking the files that i gave to it.

Here Is My HTML

 <form id="contact-form" autocomplete>
            <fieldset id="aboutYou">
                <legend>
                    About You.
                </legend>
                <label for="honorific">Honorific:</label>
                <select name="honorific" aria-label="Honorific">
                    <option value="Mr.">Mr.</option>
                    <option value="Mrs.">Mrs.</option>
                    <option value="Ms.">Ms.</option>
                    <option value="Dr.">Dr.</option>
                    <option value="Ing.">Ing.</option>
                </select>
                <label for="firstName">First Name* : </label>
                <input type="text" name="firstName" aria-label="First Name" placeholder="John." required autocomplete>
                <label for="lastName">Last Name* : </label>
                <input type="text" name="lastName" aria-label="Last Name" placeholder="Doe." required autocomplete>
                <p>Most Likely I'll Contact You By Email Unless you rather otherwise.</p>
                <label for="email">Email* : </label>
                <input type="email" name="email" aria-label="Email" placeholder="johndoe@example.com" required autocomplete>
                <label for="phone">Phone Number: </label>
                <input type="tel" name="phone" aria-label="Phone Number" placeholder="+1 (999) 999-9999" autocomplete>
            </fieldset>
            <fieldset id="aboutCompany">
                <legend>About Your Company</legend>
                <p>If you do not have a Company Please Feel Free To Let This Empty.</p>
                <label for="companyName">Company Name : </label>
                <input type="text" name="companyName" aria-label="Company Name" placeholder="Example LLC." autocomplete>
                <label for="website">Company Website : </label>
                <input type="url" name="website" aria-label="Company Website" placeholder="https://example.com" autocomplete>
                <label for="companyInfo">Tell me a bit about your company:</label>
                <textarea name="companyInfo" placeholder="Example LLC is a pretty fancy restaurant located in Canada, what makes us different is that all the customers are able to try the food instead of using a regular menu."></textarea>
            </fieldset>
            <fieldset id="aboutService">
                <legend>Select The Service(s).</legend>
                <p>Feel Free of Selecting More than one.</p>
                <div class="wrapper">
                    <div class="col-3 select-cards" role="button">
                        <i class="fas fa-code"></i>
                        <p>Web Development</p>
                    </div>
                    <div class="col-3 select-cards" role="button">
                        <i class="fas fa-tachometer-alt"></i>
                        <p>Web Optimization</p>
                    </div>
                    <div class="col-3 select-cards" role="button">
                        <i class="fab fa-connectdevelop"></i>
                        <p>Online System Development</p>
                    </div>
                    <div class="col-3 select-cards" role="button">
                        <i class="fas fa-chart-line"></i>
                        <p>S.E.O</p>
                    </div>
                    <div class="col-3 select-cards" role="button">
                        <i class="fab fa-google"></i>
                        <p>Google Marketing Suite Set Up</p>
                    </div>
                    <div class="col-3 select-cards" role="button">
                        <i class="fas fa-chart-pie"></i>
                        <p>Digital Marketing Direction</p>
                    </div>
                </div>
            </fieldset>
            <fieldset id="aboutProject">
                <legend>The Project</legend>
                <div class="wrapper">
                    <div class="col-6">
                        <textarea name="projectInfo" placeholder="Here you can Add Some Extra information about the Project if it please you."></textarea>
                    </div>
                    <div class="col-4">
                        <label for="files">Please Feel Free to add, relevant files, such as media or documents." </label>
                        <input type="file" name="files" aria-label="Add files" multiple style="border:none;">
                    </div>
                </div>
            </fieldset>
            <input type="submit" value="Lets Create Something Crazy">
        </form>

Here is My AJAX

            let files = [];
    let filing = $('input[name="files"');
    let actualFiles = [];
filing.change(function(e) {
        let tempFile = e.target.files;
        let amount = tempFile.length;
        for (let i = 0; i <= (amount - 1); i++) {
            files.push(tempFile[i].name);
            actualFiles.push(tempFile[i]);
        }
    });
            honorific = $('select[name="honorific"]').val();
            firstName = $('input[name="firstName"').val(); // required
            lastName = $('input[name="lastName"').val(); // required
            email = $('input[name="email"').val(); // required
            phone = $('input[name="phone"').val();
            companyName = $('input[name="companyName"').val();
            website = $('input[name="website"').val();
            companyInfo = $('textarea[name="companyInfo"').val();
            services = []; // required
            cards = $('.select-cards.selected');
            if (cards) {
                cards.each(function() {
                    let text = $(this).find('p').text();
                    services.push(text);
                });
            }
            projectInfo = $('textarea[name="projectInfo"').val();
$.ajax({
                method: "POST",
                url: "/leadHandler.php",
                data: {
                    "honorific": `${honorific}`,
                    "firstName": `${firstName}`,
                    "lastName": `${lastName}`,
                    "email": `${email}`,
                    "phone": `${phone}`,
                    "company": `${companyName}`,
                    "website": `${website}`,
                    "companyDescription": `${companyInfo}`,
                    "services": `${services}`,
                    "projectInfo": `${projectInfo}`,
                    "filesNames": `${files}`,
                    "files": `${actualFiles}`
                },
                success: function(responseText) {
                    console.log(`${responseText}`)
                },
                error: function(jqXHR, status, error) {
                    console.log(
                        `
                                ${jqXHR}
                                ${status}
                                ${error}
                            `
                    )
                }
            });

And here is the Handler.php

<?php
# General Variables
    $directory = "/leads/uploads";
# General Variables Ends
if (!empty($_POST['firstName'])){
    #Receiving The Data
        $honorific = $_POST['honorific'];
        $firstName = $_POST['firstName'];
        $lastName = $_POST['lastName'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $company = $_POST['company'];
        $website = $_POST['website'];
        $companyDescription = $_POST['companyDescription'];
        $services = $_POST['services'];
        $projectInfo = $_POST['projectInfo'];
        $files = $_FILES['files'];
    #Receiving The Data Ends

    #Uploading Files To Folder Function
        if (isset($files) && !empty($files)) {
            foreach ($files as $key => $error) {
                if ($error == UPLOAD_ERR_OK) {
                    $tmp_name = $files["tmp_name"][$key];
                    // basename() may prevent filesystem traversal attacks;
                    // further validation/sanitation of the filename may be appropriate
                    $name = basename($files["name"][$key]);
                    move_uploaded_file($tmp_name, $directory . "/" .$name);
                }
            }
        }
    #Uploading Files To Folder Function Ends
}
?>

With the Ajax i'm taking as many files the user uploaded in the form input and saving them into a whole array to send it later to the php file that is supposed to catch them with the $file variable.

  • 写回答

1条回答 默认 最新

  • duanqiu3800 2019-04-08 03:18
    关注

    Try This I Hope This will Works. First of all add

    enctype="multipart/form-data"

    in the Form tag

    <form id="contact-form" autocomplete enctype="multipart/form-data">
    

    And then in Ajax code write this. this code will automatically collect all fields from the form and sent the data to the leadHandler.php

     var formData = new FormData($("#contact-form")[0]); //It automatically collects all fields from form
        $.ajax({
            url: "/leadHandler.php",
            type: "post",
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(responseText) {
                     console.log(responseText);
             },
            error: function(jqXHR, status, error) {
                     console.log(jqXHR, status, error);
             }
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值