簡體   English   中英

通過Ajax將多個文件附件附加到php

[英]Multiple file attachments to php via ajax

在您判斷我之前,請知道我不是個大職業,只是想在這里學習如何做事。

我正在嘗試創建帶有多個附件的郵件表單

表格代碼

<div class="file-upload-wrapper"> 
    <label class="file-field" data-max-files="6">
        <input type="file" name="photos[]" multiple>
            <span>Drag your files here or click to select your files <span>.jpg, .png and .pdf</span></span>
    </label>
    <div class="uploaded-files"></div>
</div>

js / jQuery代碼

var photos = [];
var data;
$(document).ready ( function() {
    //Documnet Upload Script//
    function fileUpload(obj){
        var dropZone = obj.find('.file-field');
        var fileInput = dropZone.find('input[type="file"]');
        var filesBeen = obj.find('.uploaded-files');
        var maxFiles = Number(dropZone.attr('data-max-files'));

        function highlightDropZone(e){
            if(e.type == 'dragover') dropZone.addClass('highlighted');
            else dropZone.removeClass('highlighted');
            e.preventDefault();
            return false;
        }

        function filesDropped(e){
            highlightDropZone(e);
            var files = e.target.files || e.dataTransfer.files;
            for(var i = 0, file; file = files[i]; i++) {
                if(file.size <= 3000000 && (file.type == "application/pdf" || file.type == "image/jpg" || file.type == "image/jpeg" ||file.type == "image/png")) {
                    photos.push(file);
                    if (file.type == "application/pdf") {
                        var uploaded = filesBeen.prepend('<div><div><img src="images/adobe-acrobat-pdf-file-512.png"></div><span></span></div>');
                        uploaded.find('span').click(function () {
                            $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                $(this).remove()
                            });
                        });
                    } else {
                        var fReader = new FileReader();
                        fReader.onloadend = (function(f){
                            return function() {
                                if (maxFiles > Number(filesBeen.children('div').length)) {
                                    var uploaded = filesBeen.prepend('<div><div><img src="' + this.result + '"></div><p><span>' + f.name + '</span></p><span></span></div>');
                                    uploaded.find('span').click(function () {
                                        var me = $(this);
                                        $(this).closest('div').animate({width: 0, height: 0}, 200, function () {
                                            $(this).remove();
                                            me.unbind('click');
                                        });
                                    });
                                }
                            }
                        })(file);
                        fReader.readAsDataURL(file);
                    }
                }else {
                    window.alert("The size of the file is more than 3Mb or format is not supported.");
                }
            }
            console.log(photos);
        }

        dropZone.get(0).addEventListener('dragover', highlightDropZone);
        dropZone.get(0).addEventListener('dragleave', highlightDropZone);
        dropZone.get(0).addEventListener('drop', filesDropped);
        fileInput.get(0).addEventListener('change', filesDropped);
    }

    $('.file-upload-wrapper').each(function(){
        new fileUpload($(this));
    });

    $('.submit-form').click(function(e) {
        e.preventDefault();
        // Store values in variables
        var form = $('form[name="contact-form"]');

        var ip = form.find('input[name=ip]');
        var httpref = form.find('input[name=httpref]');
        var httpagent = form.find('input[name=httpagent]');

        var name = form.find('input[name=name]');
        var email = form.find('input[name=email]');
        var phone = form.find('input[name=phone]');
        var message = form.find('textarea[name=message]');

        var submitted = form.find('input[name=submitted]');
        var visitor = form.find('input[name=visitor]');
        var emails = form.find('input[name=email]').val();

        function validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        }

        if (validateEmail(emails)) {
            // Organize data
            data = new FormData();
            data.append('ip', ip.val());
            data.append('httpref', httpref.val());
            data.append('httpagent', httpagent.val());
            data.append('name', name.val());
            data.append('email', email.val());
            data.append('phone', phone.val());
            data.append('message', message.val());
            data.append('submitted', submitted.val());
            data.append('visitor', visitor.val());
            for(var i = 0; i < photos.length; i++){
                data.append('file'+i, photos[i]);
            }

            var request = $.ajax({
                type: "POST",
                dataType: 'script',
                url: "/includes/sendConatctform.php",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function (html) {
                    if (html == "true") {
                        form.find('.email-sent').fadeIn(500).delay(4000).fadeOut(500);
                    } else {
                        form.find('.email-error').fadeIn(500).delay(4000).fadeOut(500);
                    }
                },
                error: function (jqXHR, textStatus, error) {
                    alert("Form Error: " + error);
                }
            });
        } else {
            form.find('.email-results').fadeIn(500).delay(4000).fadeOut(500);
        }
        return false;
    });
});

我想做的是在PHP文件中接收附件,以進行進一步的處理。

PHP代碼

$message  = "Date: $todayis \r\n";
$message .= "From: $name ($email) \r\n";
$message .= "Phone: $phone \r\n";
$message .= "Subject: $subject \r\n";
$message .= "Message: $userMessage \r\n";
$message .= "IP Address: $ip \r\n";
$message .= "Browser Info: $httpagent \r\n";
$message .= "Referral: $httpref  \r\n";

foreach($_FILES['photos']['name'] as $file){
    $message .= "Attachments:" .$file['filename'];
}

我已經嘗試過在這里找到的建議使用ajax將多個文件附件發送到php文件

但這對我的情況沒有幫助。

你能給些建議么?

感謝所有幫助

先感謝您

由於在您的php代碼中,您要遍歷$_FILES['photos'] ,因此您應該在js代碼中進行以下更改:

data.append('file'+i, photos[i]);

data.append('photos[]', photos[i]);

更新:

另外,在您的php代碼中 ,在此處更改$file['filename']

foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" .$file['filename'];
}

只是$file

foreach($_FILES['photos']['name'] as $file){
  $message .= "Attachments:" . $file;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM