Sending additional parameter with dropzone.js
Asked Answered
C

8

42

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

Champerty answered 30/5, 2014 at 14:26 Comment(0)
M
65

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>
Masticatory answered 22/6, 2016 at 7:47 Comment(4)
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.Parang
I was trying to use this code it gives me an error like Uncaught TypeError: Cannot read property 'append' of undefinedDrynurse
@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 :)Masticatory
Still works with latest dropzone 🙌Biosynthesis
S
29

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.

Sinuation answered 20/5, 2018 at 15:50 Comment(2)
url: "/upload.php", init: function() { this.on("sending", function(file, xhr, formData) { formData.append( "data", $( '#upload-form-module input' ).serialize() ); console.log(formData); }); }, Snorkel
cleanest solution should be thisExoenzyme
S
16

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,
            });
Sabir answered 14/2, 2015 at 16:45 Comment(0)
T
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>
Tonatonal answered 9/1, 2015 at 11:15 Comment(1)
According to the docs this should work, but not if instantiating programmatically when not using a formDiaphaneity
I
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;
});
Illuminance answered 22/1, 2016 at 17:6 Comment(0)
R
3

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();
 }
Radloff answered 19/11, 2016 at 20:15 Comment(0)
M
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 }; }
};
Maxon answered 8/3, 2019 at 16:17 Comment(0)
B
2

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.

Berwickupontweed answered 8/3, 2019 at 16:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.