0
votes

I am obtaining files and their values in a non-normal way. There isn't an actual input in the form. Therefore, I am trying to append the files to the formData for ajax submission.

Anytime I try to submit the form with the method below, my files aren't uploading. Therefore, the way I am appending the files must be incorrect.

I was told the following from someone, but I can't figure out how to do it:

You're looping through the array but appending the entire array every time through the loop. Use the brackets on the form input name and append each file in the array.

Does anyone see what I need to change to get this to work?

Code for the dropzone...before the relevant code below:

var dragFileName = '';

var myDropzone = new Dropzone("#myDropzone", {
//$('#myDropzone').dropzone ({
//Dropzone.options.myDropzone= {
    url: 'php/quoteSendTest.php',
    autoProcessQueue: false,
    paramName: "file",
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 25,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    dictFileTooBig: 'File is larger than 25MB',
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
    /*  document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            console.log("Something should be showing for eventListener");
            //e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });*/

        this.on("addedfile", function(file) {
            /* Maybe display some more file information on your page */
            dragFileName = file.name;
            var dragFileSize = file.size;
            var count = myDropzone.files.length;
            console.log('File added - ' + file.name + ' - Size - ' + file.size);
            console.log(count + " is the length");
            //console.log("FILEname is " + dragFileName);
            setTimeout(function () {
                toggleUploadButton();
            }, 10);
        });

        //send all the form data along with the files:
        /*this.on("sendingmultiple", function(data, xhr, formData) {
            //formData.append("firstname", jQuery("#firstname").val());
            //formData.append("lastname", jQuery("#lastname").val());
        });
        */
    }
});

Relevant code:

var acceptedFiles = null;
var allAcceptFiles = null;

function toggleUploadButton() {
    acceptedFiles = myDropzone.getAcceptedFiles();
    allAcceptFiles = acceptedFiles.values();

    for (let fileElements of allAcceptFiles) {
        console.log(fileElements);
    }
}

function submit(){
    var form = document.getElementById("salesforce_submit");
    var formData = new FormData(form);
    fileElements.each(function() {
        formData.append('uploadedFile[]', fileElements);
    });
    alert(formData);

    $.ajax({
        url: '/php/quoteSendTest.php',
        type: 'POST',
        data: formData,

HTML:

<form action="<?php echo $config['sf_url']; ?>" method="POST" id="salesforce_submit">
    <input id="first_name" name="first_name" type="text">
    <div class="dropzone dz-clickable" id="myDropzone">
        <div class="dz-default dz-message dG">Drop files here or click to upload</div>
    </div>
    <button type="submit" id="submit-all">SEND PROJECT QUOTE</button>
</form>

Console.log info from fileElements:

File {upload: {…}, status: "queued", previewElement:

div.dz-preview.dz-file-preview, previewTemplate:

div.dz-preview.dz-file-preview, _removeLink: a.dz-remove, …} accepted:

true dataURL: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABtUA"

height: 892 lastModified: 1512405192880 lastModifiedDate: Mon Dec 04

2017 11:33:12 GMT-0500 (Eastern Standard Time) {} name:

"analytics.PNG" previewElement: div.dz-preview.dz-image-preview

previewTemplate: div.dz-preview.dz-image-preview size: 544438 status:

"queued" type: "image/png" upload: {uuid: "6dc946e7-e9db-4b3a-88af-b790de1c2975", progress: 0, total: 544438, bytesSent: 0, filename: "analytics.PNG", …} webkitRelativePath: ""

width: 1749

_removeLink: a.dz-remove

proto: File

1
You want to append each file with a unique index. You want something more like fileElements.each((index, element) => { formData.append('index', element.files); });, though I'm not sure where you're actually getting fileElements or what type of element the array contains - GammaGames
@GammaGames The console.log for fileElements results in all of the file info. See my edited question. - Paul
could you please include any html to recreate a minimal reproducable example? It would make it a lot easier to help - GammaGames
@GammaGames Sure. I don't think the HTML really helps though. I added it to the question. It seems like whenever I try appending anything to the formData or atleast with what I had before and even with your suggestion, that my AJAX submission doesn't run. The only thing that happens is the redirect from the form action. - Paul
I also added more of the javascript to my question. The part added is the dropzone code (drag and drop file upload system) that I am trying to integrate. - Paul

1 Answers

2
votes

In your initial attempt:

function toggleUploadButton() {
    acceptedFiles = myDropzone.getAcceptedFiles();
    allAcceptFiles = acceptedFiles.values();

    for (let fileElements of allAcceptFiles) {
        console.log(fileElements);
    }
}

var formData = new FormData(form);
fileElements.each(function() {
    formData.append('uploadedFile[]', fileElements);
});

You are looping through allAcceptFiles and setting each one to fileElements. This leaves fileElements as a single file, and when try to do the each loop later it doesn't act as you'd expect.

I noticed that myDropzone must be defined somewhere, since it was working in the first function. Looking at the dropzone documentation, I saw it had a getAcceptedFiles method that you could easily use to loop through and add each file to the form data. The modified loop is below:

var formData = new FormData(form);
myDropzone.getAcceptedFiles().forEach(file => {
    formData.append("uploadedFile[]", file); 
});

There are a couple other things that don't seem necessary in the code, but this isn't code review so I'll leave them alone.