javascript 使用 DropzoneJs 下载上传的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21050275/
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
Download uploaded file with DropzoneJs
提问by Vitor
I would like to know if it is possible to download files that have been uploaded with Dropzone. For example add to the file that are shown in the dropzone a link or a button to download.
我想知道是否可以下载使用 Dropzone 上传的文件。例如,向放置区中显示的文件添加要下载的链接或按钮。
The code for upload and to show the files already uploaded:
上传和显示已上传文件的代码:
index.php
索引.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
$.get('upload.php', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, "uploads/"+value.name);
});
});
thisDropzone.on("addedfile", function(file) {
var removeButton = Dropzone.createElement("<button>Remove</button>");
var _this = this;
removeButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
_this.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
thisDropzone.on("removedfile", function(file) {
if (!file.serverId) { return; }
$.post("delete-file.php?id=" + file.serverId);
});
}
};
</script>
</head>
<body>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>
</body>
</html>
upload.php
上传.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
} else {
$result = array();
$files = scandir($storeFolder);
if ( false!==$files ) {
foreach ( $files as $file ) {
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize($storeFolder.$ds.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
?>
any help will be much appreciated
任何帮助都感激不尽
采纳答案by user3206704
Yes I found it possible by altering the dropzone.js file, not ideal for updates but only way I found that worked for me.
是的,我发现它可以通过更改 dropzone.js 文件来实现,这对于更新来说并不理想,但只有我发现对我有用的方法。
Add these 6 lines of code to the addedfile: function around line 539 note Ive marked the code that exists already
将这 6 行代码添加到 addedfile: function around line 539 note Ive 标记了已经存在的代码
// the following line already exists
if (this.options.addRemoveLinks) {
/* NEW PART */
file._openLink = Dropzone.createElement("<a class=\"dz-open\" href=\"javascript:undefined;\">Open File</a>");
file._openLink.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
window.open("http://www.mywebsite.com/uploadsdirectory/"+file.name);
});
/* END OF NEW PART */
// the following lines already exist
file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
file._removeLink.addEventListener("click", function(e) {
Then you'll need to edit the CSS with a class 'dz-open', to style the button.
然后,您需要使用“dz-open”类来编辑 CSS,以设置按钮的样式。
回答by Konstantin XFlash Stratigenas
myDropzone.on("success", function(file) {
var a = document.createElement('a');
a.setAttribute('href',"/uploads/" + file.fullname);
a.innerHTML = "<br>download";
file.previewTemplate.appendChild(a);
});
回答by JSuar
This can be accomplished using the the example below. You will still need to tweak it to your needs.
这可以使用下面的示例来完成。您仍然需要根据需要对其进行调整。
I want to display additional information after a file uploaded.
To use the information sent back from the server, use the
success
event, like this:Dropzone.options.myDropzone = { init: function() { this.on("success", function(file, responseText) { // Handle the responseText here. For example, // add the text to the preview element: file.previewTemplate.appendChild(document.createTextNode(responseText)); }); } };
要使用从服务器发回的信息,请使用
success
事件,如下所示:Dropzone.options.myDropzone = { init: function() { this.on("success", function(file, responseText) { // Handle the responseText here. For example, // add the text to the preview element: file.previewTemplate.appendChild(document.createTextNode(responseText)); }); } };
回答by Rizwan Ahmed
Use this in init function after ajax call. I had the same issue. Solved using this.
在 ajax 调用后在 init 函数中使用它。我遇到过同样的问题。用这个解决了。
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr('id', "filename_" + index);
var selectFile = document.querySelector("#filename_" + index);
selectFile.addEventListener("click", function () {
window.open("http://localhost:8080/<<contextpath>>/pathtofile/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});
回答by Lars Moelleken
you can also add a empty link to your images and when your upload is ready you can fetch the image-src and set it to your link ;)
您还可以为您的图片添加一个空链接,当您准备好上传时,您可以获取 image-src 并将其设置为您的链接;)
<a href="#">
<img src="" data-dz-thumbnail/>
</a>
$("img.data-dz-thumbnail").each(function() {
$(this).closest("a").attr("href", $(this).attr("src"));
$(this).closest("a").attr("target", "_blank");
});
回答by Djomla
My code is something like this.
我的代码是这样的。
success: function(file, rawResponse){
file.previewElement.onclick = function() {
alert(1);//do download
}
},
回答by Brian Levi
Yes. I found a way by adding a custom preview template (adding a download button there and setting a data-file-id attribute). Then when defining the dropzone on the document ready, I searched for the last generated button element and modified the "data-file-id" attribute to save the file id.
是的。我通过添加自定义预览模板找到了一种方法(在那里添加一个下载按钮并设置一个 data-file-id 属性)。然后在准备好文档上定义 dropzone 时,我搜索最后生成的按钮元素并修改“data-file-id”属性以保存文件 id。
I did the same on the 'success' event of dropzone.
我对 dropzone 的“成功”事件做了同样的事情。
After this I listened to the on click event of the download button and looked for the data-file-id attribute.
在此之后,我监听了下载按钮的点击事件并查找了 data-file-id 属性。
var oakDropzone = new Dropzone("#oakDropzone", {
url: "/trabajo/uploadFile",
init: function () {
var trabajoId = $("#trabajoId").val();
var getArchivosUrl = "/trabajo/getArchivosByTrabajo?trabajoId=" + trabajoId;
$("#fileLoader").show();
$.get(getArchivosUrl)
.done(function (response) {
for (var i = 0; i < response.data.length; i++) {
var file = response.data[i];
var fileData = { id: file.Id, name: file.Nombre, size: file.Tama?o, metadata: file.Metadata };
fileData.accepted = true;
oakDropzone.files.push(fileData);
oakDropzone.emit('addedfile', fileData);
oakDropzone.emit('thumbnail', fileData, 'data:' + response.data[i].Extension + ';base64,' + response.data[i].Preview);
oakDropzone.emit('complete', fileData);
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', fileData.id);
}
$("#fileLoader").hide();
$('#oakDropzone #template .dz-details .actionButtons .downloadFile').on('click', function (event) {
event.preventDefault();
var archivoId = $(this).data('file-id');
var downloadUrl = "http://localhost:11154/trabajo/downloadFile?fileId=" + archivoId;
window.open(downloadUrl, 'blank');
});
}).catch(function (response) {
displayErrorToaster(response);
});
this.on("sending", function (file, xhr, formData) {
formData.append("Id", trabajoId);
formData.append("File", file);
});
this.on("success", function (file, response) {
file.id = response.data;
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', file.id);
displaySuccessToaster(response);
});
this.on("removedfile", function (file) {
var deleteUrl = "/trabajo/RemoveFile?fileId=" + file.id;
$.post(deleteUrl)
.done(function (response) {
displaySuccessToaster(response);
}).catch(function (response) {
displayErrorToaster(response);
});
});
},
dictRemoveFileConfirmation: 'Realmente desea quitar el archivo seleccionado?',
dictDefaultMessage: '',
clickable: "#btnUploadFile",
previewTemplate: document.querySelector('#previews').innerHTML,
addRemoveLinks: false
});
This looks like the following image:
这看起来像下图:
Hope this helps you!.
希望这对你有帮助!。