Javascript 上传时的 Dropzone 提交按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46728205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dropzone Submit Button on Upload
提问by Gael Musikingala
I want to add a button upload to my dropzone file uploader. currently it's uploading the file directly after selecting or dragging the file into the dropzone area. What I want to do is: 1. Select or drap file to be uploaded. 2. Validate 3. Hit or press the button upload to upload the file.
我想向我的 dropzone 文件上传器添加一个按钮上传。目前它是在选择文件或将文件拖入拖放区区域后直接上传文件。我想要做的是: 1. 选择或拖放要上传的文件。2. 验证 3. 点击或按下上传按钮上传文件。
N.B: File is only being uploaded after pressing the button upload.
注意:文件只有在按下上传按钮后才被上传。
Here is my form
这是我的表格
<form id='frmTarget' name='dropzone' action='upload_files.php' class='dropzone'>
<div class='fallback'>
<input name='file' type='file' multiple />
</div>
<input id='refCampaignID' name='refCampaignID' type='hidden' value=\ "$rowCampaign->CampaignID\" />
</form>
Here is my JS
这是我的 JS
Dropzone.options.frmTarget =
{
url: 'upload_files.php',
paramName: 'file',
clickable: true,
maxFilesize: 5,
uploadMultiple: true,
maxFiles: 2,
addRemoveLinks: true,
acceptedFiles: '.png,.jpg,.pdf',
dictDefaultMessage: 'Upload your files here',
success: function(file, response)
{
setTimeout(function() {
$('#insert_pic_div').hide();
$('#startEditingDiv').show();
}, 2000);
}
};
Here is my php post request
这是我的 php 帖子请求
foreach ($_FILES["file"] as $key => $arrDetail)
{
foreach ($arrDetail as $index => $detail) {
//print_rr($_FILES["file"][$key][$index]);
$targetDir = "project_images/";
$fileName = $_FILES["file"]['name'][$index];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES["file"]['tmp_name'][$index],$targetFile))
{
$db = new ZoriDatabase("tblTarget", $_REQUEST["TargetID"], null, 0);
$db->Fields["refCampaignID"] = $_REQUEST["refCampaignID"];
$db->Fields["strPicture"] = $fileName;
$db->Fields["blnActive"] = 1;
$db->Fields["strLastUser"] = $_SESSION[USER]->USERNAME;
$result = $db->Save();
if($result->Error == 1){
return "Details not saved.";
}else{
return "Details saved.";
}
}else{
return "File not uploaded.";
}
}
}
回答by Don't Panic
You need to:
你需要:
Add a button:
<button type="submit" id="button" class="btn btn-primary">Submit</button>Tell Dropzone notto automatically upload the file when you drop it, as it will by default. That's done with the
autoProcessQueueconfig option:autoProcessQueue: falseSince Dropzone will now not auto-upload the files, you need to manually tell it to do that when you click your button. So you need an event handler for that button click, which tells Dropzone to do the upload:
$("#button").click(function (e) { e.preventDefault(); myDropzone.processQueue(); });That will just POST the uploaded file, without any of your other input fields. You probably want to post all fields, eg your
refCampaignID, a CSRF token if you have one, etc. To do that, you need to copy them into the POST before sending. Dropzone has asendingeventwhich is called just before each file is sent, where you can add a callback:this.on('sending', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); });
添加按钮:
<button type="submit" id="button" class="btn btn-primary">Submit</button>告诉 Dropzone在您放下文件时不要自动上传文件,因为默认情况下它会这样做。这是通过配置选项完成的
autoProcessQueue:autoProcessQueue: false由于 Dropzone 现在不会自动上传文件,因此您需要在单击按钮时手动告诉它这样做。所以你需要一个按钮点击的事件处理程序,它告诉 Dropzone 进行上传:
$("#button").click(function (e) { e.preventDefault(); myDropzone.processQueue(); });这只会发布上传的文件,没有任何其他输入字段。您可能想要发布所有字段,例如您的
refCampaignID,CSRF 令牌(如果您有的话)等等。为此,您需要在发送之前将它们复制到 POST 中。Dropzone 有一个在发送每个文件之前调用的sending事件,您可以在其中添加回调:this.on('sending', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); });
Putting it all together:
把它们放在一起:
Dropzone.options.frmTarget = {
autoProcessQueue: false,
url: 'upload_files.php',
init: function () {
var myDropzone = this;
// Update selector to match your button
$("#button").click(function (e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on('sending', function(file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('#frmTarget').serializeArray();
$.each(data, function(key, el) {
formData.append(el.name, el.value);
});
});
}
}
回答by Nathan
Thought I'd add a pure vanilla JS solution as well, no jQuery.
以为我也会添加一个纯香草 JS 解决方案,没有 jQuery。
/* 'dropform' is a camelized version of your dropzone form's ID */
Dropzone.options.dropform = {
/* Add all your configuration here */
autoProcessQueue: false,
init: function()
{
let myDropzone = this;
/* 'submit-dropzone-btn' is the ID of the form submit button */
document.getElementById('submit-dropzone-btn').addEventListener("click", function (e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on('sending', function(file, xhr, formData)
{
/* OPTION 1 (not recommended): Construct key/value pairs from inputs in the form to be sent off via new FormData
'dropform' is the ID of your dropzone form
This method still works, but it's submitting a new form instance. */
formData = new FormData(document.getElementById('dropform'));
/* OPTION 2: Append inputs to FormData */
formData.append("input-name", document.getElementById('input-id').value);
});
}
};
NOTE:Setting up Event Listeners such as the sendingone we are doing here should be put inside the initfunction. If you were to place them elsewhere, for example:
注意:设置事件侦听器(例如sending我们在这里所做的)应该放在init函数中。如果您要将它们放在其他地方,例如:
init: function()
{
//...
},
sending: function(file, xhr, formData)
{
//... logic before each file send
}
this will override the default logic dropzone provides for the sendingEvent listener, and can cause unintended side effects. You should only do this if you know what you're doing.
这将覆盖为sending事件侦听器提供的默认逻辑 dropzone ,并可能导致意外的副作用。只有当您知道自己在做什么时,才应该这样做。

