简体   繁体   中英

Multiple file attachments to php via ajax

Before you judge me please know that I am not a big pro and just trying to learn how to do things here.

I am trying to create a mailing form with multiple attachments

form code

<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 code

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;
    });
});

What I am trying to do is to receive the attachments in my PHP file for further proceedings.

php code

$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'];
}

I have tried the suggestion that I have found here Send multiple file attachments to php file using ajax

but it did not help with my situation.

can you please advise?

All help is appreciated

Thank you in advance

Since in your php code you are iterating over $_FILES['photos'] , then you should change in your js code this:

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

to

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

Update:

Also, in your php code change $file['filename'] here:

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

to just $file :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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