Подтвердить что ты не робот

Отправка дополнительного параметра с помощью dropzone.js

Я пытаюсь добавить dropzone.js, и я хотел бы передать еще один параметр с файлом, поэтому я помещаю скрытый ввод в форму. Я могу загрузить файл и прочитать его в Java-части, но я не могу прочитать 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

Поэтому, если я напишу;

 request.getParameter("type_chooser");

Я получаю null

Как я могу получить type_chooser?

Примечание: я попробовал;

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

Это дает тот же результат со скрытым полем в форме dropzone, оба они отправляют type_chooser, но я не могу его прочитать в java

4b9b3361

Ответ 1

Вы можете добавлять данные вместе с 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>

Ответ 2

Мой был похож на Сахина Яньлыка

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.on("sending", function(file, xhr, data) {
                        data.append("filetype", "avataruploadtype");
                    });

КОНЕЦ

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

Ответ 3

попробуйте добавить его в свой список параметров доступа, как этот

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

Ответ 4

У меня была одна и та же проблема, я не смог ее прочитать в java

Поэтому я пробовал это, и это сработало.

contentDropZone.on('processing', function(file){
    console.log("Processing the file");
    contentDropZone.options.url = "Uploader?campaignid="+campaignid+"&circleid="+circleid;
});

Ответ 5

Это полная рабочая зона с дополнительными параметрами, потому что другие методы, найденные в Интернете, не работают для меня.

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

Ответ 6

Привет, у меня была такая же проблема после того, как много исследований нашло это решение, работало для меня, я использую jQuery dropzone.

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

params - это то, что я нашел для отправки дополнительных данных с dropzone. params параметров params получены в $_POST и загружены в файл $_FILE.

Надеюсь это поможет.