40

I am trying to add dropzone.js and I'd like to pass another parameter with file, so I put hidden input in form . I can upload file and can read it in Java part but I can't read type_chooser,

  ------WebKitFormBoundaryZxF6MCYJpTOLUokN
 Content-Disposition: form-data; name="type_chooser"

 2
 ------WebKitFormBoundaryZxF6MCYJpTOLUokN
 Content-Disposition: form-data; name="file"; filename="isci.xlsx"
 Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

So if I write;

 request.getParameter("type_chooser");

I get null

How can I get type_chooser ?

Note : I tried ;

  dropzone.on("sending,function(file,xhr,data){
     data.append("type_chooser","1");
  });

This gives same output with hidden field in dropzone form, both of them are sending type_chooser but I can't read it in java

Aaron Fahey
  • 699
  • 1
  • 7
  • 20
Sahin Yanlık
  • 1,171
  • 2
  • 11
  • 21

8 Answers8

61

You can append data along with the formdata

 $("div#dropzone_profile_photo").dropzone({
            url: "/file-upload/",
            init: function() {
                this.on("sending", function(file, xhr, formData){
                        formData.append("data", "loremipsum");
                });
            }
        });

$("div#dropzone_profile_photo").dropzone({
  url: "/test",
  init: function() {
    this.on("sending", function(file, xhr, formData) {
      formData.append("data", "loremipsum");
      console.log(formData)
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">
<div id="dropzone_profile_photo" style="width:400px;height:400px; background-color:blue"></div>
Iceman
  • 6,035
  • 2
  • 23
  • 34
  • 2
    Cleanest solution by far! The other solutions add params to the URL, which browsers and load balancers may cache (been there, sucks to debug). Using it as a POST form parameter is perfect. – Gawin Aug 03 '16 at 10:20
  • I was trying to use this code it gives me an error like `Uncaught TypeError: Cannot read property 'append' of undefined` – Akshay Shrivastav Oct 17 '17 at 11:52
  • @AkshayShrivastav not sure...what you are doing wrong..I have added an example to confirm this solution still works. Consider, posting a snippet here if you still think the solution is wrong...if not remove your down-vote :) – Iceman Oct 18 '17 at 04:39
  • Still works with latest dropzone – aidan Jun 20 '23 at 17:54
27

Hi i had same problem after lot of research found this solution, worked for me i am using jQuery dropzone.

$("#dropzone").dropzone({
    url: "abcd.php",
    dictDefaultMessage: "Drop files here or<br>click to upload...",
    params: {'param_1':'xyz','para_2':'aaa'}
});

the params option is what i found to send additional data with dropzone. the params option parametes are received in $_POST and uploaded file in $_FILE.

Hope this helps.

Ajaypratap
  • 281
  • 3
  • 8
  • `url: "/upload.php", init: function() { this.on("sending", function(file, xhr, formData) { formData.append( "data", $( '#upload-form-module input' ).serialize() ); console.log(formData); }); }, ` – Camaleo May 02 '21 at 13:16
  • cleanest solution should be this – Kent Liau Feb 21 '22 at 14:25
15

Mine was similar to Sahin Yanlık

var myDropzone = new Dropzone(dropzoneid,
            {
                url: "/files/post",
                acceptedFiles: 'image/*',
                paramName: "file", // The name that will be used to transfer the file
                maxFilesize: 1, // MB
                maxFiles: 1,
                init: function () {

                    // Using a closure.
                    var _this = this;

                    // Setup the observer for the button.
                    $("#clear-dropzone").on("click", function () {
                        // Using "_this" here, because "this" doesn't point to the dropzone anymore
                        _this.removeAllFiles();
                        // If you want to cancel uploads as well, you
                        // could also call _this.removeAllFiles(true);
                    });
                    //this.on("maxfilesexceeded", function (file)
                    //{
                    //    this.removeFile(file);
                    //});

START (This is the override to send in additional data)

                    this.on("sending", function(file, xhr, data) {
                        data.append("filetype", "avataruploadtype");
                    });

END

                    this.on("addedfile", function() {
                        if (this.files[1] != null) {
                            this.removeFile(this.files[0]);
                        }
                    });
                    this.on("removedfile", function (file) {
                        //html manipulation to disable and select certain page stuff
                    });
                    this.on("success", function (file) {
                         //html manipulation to disable and select certain page stuff                    });
                },
                accept: function (file, done) {
                    if (file.name == "justinbieber.jpg") {
                        done("Naha, you don't."); //just in case!!!!
                    } else {
                        //console.log("done!!!");
                        console.log(done());
                    }
                },
                headers: { "avatar": "avatarupload" }, //you might be also to piggyback of the headers in serverside
                uploadMultiple: false,
                clickable: true,
                addRemoveLinks: true,
            });
Adam
  • 1,203
  • 1
  • 13
  • 16
9

try adding it into your get parameter list like this

<form action="/UnitSummary/UploadFile?param1=value&param2=value" class="dropzone" enctype="multipart/form-data" id="imgUpload" method="post">
    <div class="fallback">
        <input name="file" type="file" multiple />
        <input type="submit" value="Upload" />
    </div>
</form>
Lonare
  • 3,581
  • 1
  • 41
  • 45
  • According to the docs this should work, but not if instantiating programmatically when not using a form – stef Apr 23 '17 at 14:21
3

I was having a same issue, I was not able to read it in java

So i tried this and it worked.

contentDropZone.on('processing', function(file){
    console.log("Processing the file");
    contentDropZone.options.url = "Uploader?campaignid="+campaignid+"&circleid="+circleid;
});
vkscool
  • 1,419
  • 1
  • 10
  • 5
2

This is a complete working dropzone with extra parameters because other methods found online didn't work for me.

Dropzone.autoDiscover = false;
var valid_extensions=  /(\.pdf|\.doc|\.docx|\.xls|\.xlsx|\.jpg|\.jpeg|\.png|\.tiff|\.wpd)$/i;

    $('#insurance_type').on('change',function(){
        ins_Type=$(this).val();          
    });
    $('#insurance_expirationdate').on('change',function(){
        ins_Date=$(this).val();          
    });

myDropzone = new Dropzone("#dropzdoc",{
 url: 'Your URL where to send the data to',


 //this is how extra parameters got passed to dropzone

 sending: function(file, xhr, formData) {
   formData.append("insurance_type", ins_Type);  //name and value
   formData.append("insurance_expirationdate", ins_Date); //name and value

},

 //end of sending extra parameters

 acceptedFiles:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.tiff,.wpd",
 dictInvalidFileType: "You can't upload files of this type, only png or jpg file",
 paramName: "insurance_doc",
 createImageThumbnails:false,
 dictDefaultMessage: "<div style='text-align:left;'>- Select your Insurance Type.<br>\n\
                      - Select 1 Date.<br>\n\
                      - Drop your file here.<br><div>\n\
                       Only <span style='color:red;'>1</span> file is    acccepted.",
 autoProcessQueue:false,
 maxFiles: 1
});

myDropzone.on("processing", function(file, progress) {
    $('#upload_process').fadeIn();

});

myDropzone.on("success", function(file,response) {
    $('#upload_process').fadeOut();

  });

myDropzone.on("addedfile", function(file) {
//test extension files
    if (this.files.length) {
        var _i, _len;
        for (_i = 0, _len = this.files.length; _i < _len; _i++)
        {
            if(valid_extensions.test(this.files[_i].name)==false)               
                {
                   alert('Invalid file extension.\nAllowed file extensions: pdf, doc, docx, xls, xlsx, jpg, jpeg, png, tiff, wpd');
                   this.removeFile(file); 
                   return;
                }
        }
; 


 //if all good then procced the queue
    if(ins_Type !==''&& ins_Date !==''){
            this.options.autoProcessQueue = true;
            this.processQueue();         
    }else{

        alert('Date are empty');
        this.removeAllFiles(file); 
    }
  });

  //dropzone willl  be clickable after this action below
$('.files-list').on('click','img', function(){ 
            if($('.files-list li img').length == 0){
                myDropzone.removeAllFiles(true);

                myDropzone.setupEventListeners();  
            }

});
  //dropzone will not be clickable after this action below
 if($('.files-list li').children('img').length > 0){
      myDropzone.removeEventListeners();
 }
gizmo
  • 31
  • 1
2

Use params: function params(files, xhr, chunk) { return { '_token' : __csrf_token }; } options as shown in the example-codeblock bellow.

Dropzone.options.uploadDropzone = {
    paramName: "__NAME",
    maxFilesize: 6,
    thumbnailWidth: 400,
    thumbnailHeight: 400,
    dictDefaultMessage: 'Drop or Paste here.',
    params: function params(files, xhr, chunk) { return { '_token' : __csrf_token }; }
};
edam
  • 910
  • 10
  • 29
1

well, just for those who reach this thread as late as I did, I'll leave the answer from the tips section of the docs:

Dropzone will submit any hidden fields you have in your dropzone form. So this is an easy way to submit additional data. You can also use the params option.