Ben*_*son 158 html javascript jquery file-upload dropzone.js
我目前有一个HTML表单,用户可以填写他们希望发布的广告的详细信息.我现在希望能够添加一个dropzone来上传待售商品的图片.我发现dropzone.js似乎完成了我需要的大部分工作.但是,在查看文档时,您似乎需要将整个表单的类指定为"dropzone"(而不仅仅是输入元素).这意味着我的整个表格成为了dropzone.是否可以在我的表单的一部分中使用dropzone,即仅将元素指定为类dropzone,而不是整个表单?
我可以使用单独的表单,但我希望用户能够通过一个按钮提交所有表单.
或者,是否有另一个库可以做到这一点?
非常感谢
Sat*_*ngh 58
这是另一种方法:div在表单中添加带有classname dropzone的a,并以编程方式实现dropzone.
HTML:
<div id="dZUpload" class="dropzone">
<div class="dz-default dz-message"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
JQuery的:
$(document).ready(function () {
Dropzone.autoDiscover = false;
$("#dZUpload").dropzone({
url: "hn_SimpeFileUploader.ashx",
addRemoveLinks: true,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
}
});
});
Run Code Online (Sandbox Code Playgroud)
注意:禁用autoDiscover,否则Dropzone将尝试连接两次
博客文章 :Dropzone js + Asp.net:上传批量图片的简便方法
mrt*_*mgs 35
我有完全相同的问题,发现Varan Sinayee的答案是唯一一个真正解决了原始问题的答案.这个答案可以简化,所以这里是一个更简单的版本.
步骤是:
创建一个普通的表单(不要忘记方法和enctype args,因为它不再由dropzone处理).
把div放在里面class="dropzone"(这就是Dropzone附加到它上面)和id="yourDropzoneName"(用于更改选项).
设置Dropzone的选项,设置将发布表单和文件的URL,取消激活autoProcessQueue(因此只有在用户按下'submit'时才会发生)并允许多次上传(如果需要).
单击提交按钮时,将init函数设置为使用Dropzone而不是默认行为.
仍然在init函数中,使用"sendingmultiple"事件处理程序沿文件发送表单数据.
沃利亚!您现在可以像使用普通表单一样检索数据,在$ _POST和$ _FILES中(在示例中,这将在upload.php中发生)
HTML
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="text" id ="firstname" name ="firstname" />
<input type="text" id ="lastname" name ="lastname" />
<div class="dropzone" id="myDropzone"></div>
<button type="submit" id="submit-all"> upload </button>
</form>
Run Code Online (Sandbox Code Playgroud)
JS
Dropzone.options.myDropzone= {
url: 'upload.php',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
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.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//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());
});
}
}
Run Code Online (Sandbox Code Playgroud)
Var*_*yee 20
"dropzone.js"是上传图片最常用的库.如果您希望将"dropzone.js"作为表单的一部分,则应执行以下步骤:
1)对于客户端:
HTML:
<form action="/" enctype="multipart/form-data" method="POST">
<input type="text" id ="Username" name ="Username" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
Run Code Online (Sandbox Code Playgroud)
JQuery的:
<script>
Dropzone.options.myDropzone = {
url: "/Account/Create",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
wrapperThis.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("Username", $("#Username").val());
});
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
2)对于服务器端:
ASP.Net MVC
[HttpPost]
public ActionResult Create()
{
var postedUsername = Request.Form["Username"].ToString();
foreach (var imageFile in Request.Files)
{
}
return Json(new { status = true, Message = "Account created." });
}
Run Code Online (Sandbox Code Playgroud)
kab*_*mus 11
Enyo的教程很棒.
我发现教程中的示例脚本适用于嵌入dropzone的按钮(即表单元素).如果你希望在表单元素之外使用按钮,我可以使用click事件完成它:
首先,HTML:
<form id="my-awesome-dropzone" action="/upload" class="dropzone">
<div class="dropzone-previews"></div>
<div class="fallback"> <!-- this is the fallback if JS isn't working -->
<input name="file" type="file" multiple />
</div>
</form>
<button type="submit" id="submit-all" class="btn btn-primary btn-xs">Upload the file</button>
Run Code Online (Sandbox Code Playgroud)
然后,脚本标签....
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 25,
maxFiles: 25,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// Here's the change from enyo's tutorial...
$("#submit-all").click(function (e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
除了sqram所说的以外,Dropzone还有一个未公开的选项“ hiddenInputContainer”。您所要做的就是将此选项设置为希望将隐藏文件字段附加到的表单的选择器。瞧!Dropzone通常添加到身体的“ .dz-hidden-input”文件字段会神奇地移动到您的窗体中。无需更改Dropzone源代码。
现在,尽管这可以将Dropzone文件字段移动到表单中,但该字段没有名称。因此,您需要添加:
_this.hiddenFileInput.setAttribute("name", "field_name[]");
Run Code Online (Sandbox Code Playgroud)
在此行之后放到dropzone.js:
_this.hiddenFileInput = document.createElement("input");
Run Code Online (Sandbox Code Playgroud)
在第547行附近。
我想在这里提供一个答案,因为我也遇到了同样的问题 - 我们希望 $_FILES 元素作为另一个表单的同一帖子的一部分可用。我的回答基于@mrtnmgs,但请注意添加到该问题的评论。
首先:Dropzone 通过 ajax 发布数据
仅仅因为您使用该formData.append选项仍然意味着您必须处理 UX 操作 - 即这一切都发生在幕后,而不是典型的表单发布。数据发布到您的url参数。
其次:如果您因此想要模仿表单发布,您将需要存储发布的数据
这需要服务器端代码将您的$_POST或存储$_FILES在一个会话中,该会话在另一个页面加载时可供用户使用,因为用户不会转到接收发布数据的页面。
第三:您需要将用户重定向到处理此数据的页面
现在您已经发布了数据并将其存储在会话中,您需要在附加页面中为用户显示/操作它。您还需要将用户发送到该页面。
所以对于我的例子:
【Dropzone代码:使用Jquery】
$('#dropArea').dropzone({
url: base_url+'admin/saveProject',
maxFiles: 1,
uploadMultiple: false,
autoProcessQueue:false,
addRemoveLinks: true,
init: function(){
dzClosure = this;
$('#projectActionBtn').on('click',function(e) {
dzClosure.processQueue(); /* My button isn't a submit */
});
// My project only has 1 file hence not sendingmultiple
dzClosure.on('sending', function(data, xhr, formData) {
$('#add_user input[type="text"],#add_user textarea').each(function(){
formData.append($(this).attr('name'),$(this).val());
})
});
dzClosure.on('complete',function(){
window.location.href = base_url+'admin/saveProject';
})
},
});
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过从放置区捕获“发送”事件来修改 formData。
dropZone.on('sending', function(data, xhr, formData){
formData.append('fieldname', 'value');
});
Run Code Online (Sandbox Code Playgroud)
为了在单个请求中将所有文件与其他表单数据一起提交,您可以将 Dropzone.js 临时隐藏input节点复制到您的表单中。您可以在addedfiles事件处理程序中执行此操作:
var myDropzone = new Dropzone("myDivSelector", { url: "#", autoProcessQueue: false });
myDropzone.on("addedfiles", () => {
// Input node with selected files. It will be removed from document shortly in order to
// give user ability to choose another set of files.
var usedInput = myDropzone.hiddenFileInput;
// Append it to form after stack become empty, because if you append it earlier
// it will be removed from its parent node by Dropzone.js.
setTimeout(() => {
// myForm - is form node that you want to submit.
myForm.appendChild(usedInput);
// Set some unique name in order to submit data.
usedInput.name = "foo";
}, 0);
});
Run Code Online (Sandbox Code Playgroud)
显然,这是一种依赖于实现细节的解决方法。相关源代码。
我对此有一个更自动化的解决方案。
<form role="form" enctype="multipart/form-data" action="{{ $url }}" method="{{ $method }}">
{{ csrf_field() }}
<!-- You can add extra form fields here -->
<input hidden id="file" name="file"/>
<!-- You can add extra form fields here -->
<div class="dropzone dropzone-file-area" id="fileUpload">
<div class="dz-default dz-message">
<h3 class="sbold">Drop files here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
<!-- You can add extra form fields here -->
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
Dropzone.options.fileUpload = {
url: 'blackHole.php',
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
Run Code Online (Sandbox Code Playgroud)
// Get file content
$file = base64_decode(request('file'));
Run Code Online (Sandbox Code Playgroud)
无需禁用DropZone Discovery,普通表单提交将能够通过标准表单序列化将文件与任何其他表单字段一起发送。
处理后,此机制将文件内容作为base64字符串存储在隐藏的输入字段中。您可以通过标准base64_decode()方法将其解码回PHP中的二进制字符串。
我不知道这种方法是否会因为大文件而受损,但它可以处理约40MB的文件。