1.1 dropzone上传下载使用
参考博客:https://www.cnblogs.com/fu-yong/p/9053515.html
1、使用dropzone需要引入文件
<link rel="stylesheet" href="/static/dropzone/dropzone.css">
<script src="/static/dropzone/jquery-1.12.4.js"></script>
<script src="/static/dropzone/dropzone.js"></script>
2、我们可以自己写css覆盖dropzone.css 的样式
<style> #filedropzone{ width: 900px; height: 220px; margin-left: 200px; margin-top: 100px; border: 3px dashed green; border-radius: 2%; box-shadow: 3px 3px 5px #888888; } </style>
3、dropzone中引入或不引入jquery的写法
1、如果没有引入jquery:
var myDropzone = new Dropzone("div#mydropzone", {url: "/upload"});
2、如果引入了jquery:
$("#dropz").dropzone({url: "/upload"})
1.2 dropzone使用常用配置项
1、常用事件:
addedfile : 添加文件是发生
removefile : 手动从服务器删除文件时发生
success : 上传成功后发生
complete: 当文件上传成功或失败之后发生。
canceled: 当文件在上传时被取消的时候发生。
maxfilesreached: 当文件数量达到最大时发生。
maxfilesexceeded: 当文件数量超过限制时发生。
totaluploadprogress : 文件上传中的返回值,第一个参数为总上传进度(0到100),第二个为总字节数,第三个为总上传字节数,利用这几个参数,可计算出上传速度,和剩余上传时间;
2、常用的配置项:
url : 必要参数,文件的上传地址;
maxFiles : 默认为null,可以指定为一个数值,限制最多文件数量。
maxFilesize : 限制文件的大小,单位是MB;
acceptedFiles : 允许上传的文件类型,文件扩展名以逗号隔开,格式见实例;
autoProcessQueue : 默认为true,即拖入文件立即自动上传;如果需要在上传之前有一些选择的操作,然后手动上传,可以把该属性设置为false,然后手动点击按钮上传;
paramName : 相当于<input>元素的name属性,默认为file。
3、提示文本:
dictDefaultMessage : 没有任何文件被添加时的提示文本;
dictFallbackMessage: Fallback 情况下的提示文本。
dictInvalidInputType: 文件类型被拒绝时的提示文本。
dictFileTooBig: 文件大小过大时的提示文本。
dictCancelUpload: 取消上传链接的文本。
dictCancelUploadConfirmation: 取消上传确认信息的文本。
dictRemoveFile: 移除文件链接的文本。
dictMaxFilesExceeded: 超过最大文件数量的提示文本。
4、dropzone 基本事例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/dropzone/dropzone.css"> <script src="/static/dropzone/jquery-1.12.4.js"></script> <script src="/static/dropzone/dropzone.js"></script> </head> <body> <p style="font-weight: bold">上传附件</p> <form id="filedropzone" method="post" action="" class="dropzone dz-clickable" >{% csrf_token %} <div class="dz-default dz-message"> <div class="dz-icon icon-wrap icon-circle icon-wrap-md"> <i class="fa fa-cloud-upload fa-3x"></i> </div> <div> <p class="dz-text">把附件信息拖放到这里</p> <p class="text-muted">最多可上传十个附件</p> </div> </div> <input type="button" id="qr" value="上传"> <input type="button" id="cancel" value="取消"> </form> <div id="upload-div" style="margin-top: 20px"> </div> <script> //Dropzone Configuration Dropzone.autoDiscover = false; $(document).ready(function () { $("#filedropzone").dropzone({ url: '/workflow/workorder/upfile/', maxFiles: 10, // 总共可以上传文件最大个数 maxFilesize: 200, // 上传文件最大 Mb acceptedFiles: ".jpg,.jpeg,.doc,.docx,.ppt,.pptx,.txt,.avi,.pdf,.mp3,.zip", autoProcessQueue: false, paramName: "file", dictDefaultMessage: "拖入需要上传的文件", parallelUploads: 10, // 点击上传,一次上次最大个数 dictFileTooBig:"文件过大上传文件最大支持.", init: function () { var myDropzone = this, submitButton = document.querySelector("#qr"), cancelButton = document.querySelector("#cancel"); myDropzone.on('addedfile', function (file) { //添加上传文件的过程,可再次弹出弹框,添加上传文件的信息 }); myDropzone.on('sending', function (data, xhr, formData) { //向后台发送该文件的参数 formData.append('watermark', jQuery('#info').val()); }); myDropzone.on('success', function (files, response) { //文件上传成功之后的操作 {# console.log('filex upload done...', response);#} upfile_sucess(files, response) }); myDropzone.on('error', function (files, response) { //文件上传失败后的操作 }); myDropzone.on('totaluploadprogress', function (progress, byte, bytes) { //progress为进度百分比 $("#pro").text("上传进度:" + parseInt(progress) + "%"); //计算上传速度和剩余时间 var mm = 0; var byte = 0; var tt = setInterval(function () { mm++; var byte2 = bytes; var remain; var speed; var byteKb = byte / 1024; var bytesKb = bytes / 1024; var byteMb = byte / 1024 / 1024; var bytesMb = bytes / 1024 / 1024; if (byteKb <= 1024) { speed = (parseFloat(byte2 - byte) / (1024) / mm).toFixed(2) + " KB/s"; remain = (byteKb - bytesKb) / parseFloat(speed); } else { speed = (parseFloat(byte2 - byte) / (1024 * 1024) / mm).toFixed(2) + " MB/s"; remain = (byteMb - bytesMb) / parseFloat(speed); } $("#dropz #speed").text("上传速率:" + speed); $("#dropz #time").text("剩余时间" + arrive_timer_format(parseInt(remain))); if (bytes >= byte) { clearInterval(tt); if (byteKb <= 1024) { $("#dropz #speed").text("上传速率:0 KB/s"); } else { $("#dropz #speed").text("上传速率:0 MB/s"); } $("#dropz #time").text("剩余时间:0:00:00"); } }, 1000); }); submitButton.addEventListener('click', function () { //点击上传文件 myDropzone.processQueue(); }); cancelButton.addEventListener('click', function () { //取消上传 myDropzone.removeAllFiles(); }); } }); //剩余时间格式转换: function arrive_timer_format(s) { var t; if (s > -1) { var hour = Math.floor(s / 3600); var min = Math.floor(s / 60) % 60; var sec = s % 60; var day = parseInt(hour / 24); if (day > 0) { hour = hour - 24 * day; t = day + "day " + hour + ":"; } else t = hour + ":"; if (min < 10) { t += "0"; } t += min + ":"; if (sec < 10) { t += "0"; } t += sec; } return t; } }); function upfile_sucess(files, response) { response = JSON.parse(response); var up_filename = response.up_filename; var filepath = response.filepath; // 创建div var file_div = document.createElement('div'); file_div.className = "form-group has-success has-feedback"; // 创建input var input = document.createElement('input'); input.className = "form-control up-file"; input.setAttribute("value",up_filename); input.setAttribute("filepath",filepath); input.setAttribute('disabled','disabled'); // 创建span var span = document.createElement('span'); span.className = "glyphicon glyphicon-ok form-control-feedback"; file_div.appendChild(input); file_div.appendChild(span); document.getElementById('upload-div').appendChild(file_div); } </script> </body> </html>
1.3 dropzone结合django实现多文件上传下载
STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) UPLOAD_ANNEX_PATH = os.path.join(BASE_DIR, "upload/")
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^upload/', views.upload_file), url(r'^download/', views.download_file), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,HttpResponse from django.http.response import StreamingHttpResponse import uuid,json from updown_load.settings import UPLOAD_ANNEX_PATH def upload_file(request): if request.method == 'POST': filelist = request.FILES.getlist('file') data = {} if filelist: filelist = request.FILES.getlist('file') for upfile in filelist: up_filename = upfile.name store_filename = str(uuid.uuid1()) + '.' + up_filename.split('.')[-1] filepath = UPLOAD_ANNEX_PATH + store_filename with open(filepath, 'wb') as f: for item in upfile.chunks(): f.write(item) data = {'up_filename':up_filename,'filepath':filepath} print json.dumps(data) return HttpResponse(json.dumps(data) ) return render(request, 'upload.html') def download_file(request): file_path = request.GET.get('file_path') name = request.GET.get('up_filename') def file_iterator(file_path, chunk_size=512): with open(file_path, 'rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break response = StreamingHttpResponse(file_iterator(file_path)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(name.encode('utf-8').decode('ISO-8859-1')) return response
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/dropzone/dropzone.css"> <link rel="stylesheet" href="/static/bootstrap/bootstrap.min.css"> <script src="/static/dropzone/jquery-1.12.4.js"></script> <script src="/static/dropzone/dropzone.js"></script> </head> <body> <p style="font-weight: bold">上传附件</p> <form id="filedropzone" method="post" action="" class="dropzone dz-clickable" >{% csrf_token %} <div class="dz-default dz-message"> <div class="dz-icon icon-wrap icon-circle icon-wrap-md"> <i class="fa fa-cloud-upload fa-3x"></i> </div> <div> <p class="dz-text">把附件信息拖放到这里</p> <p class="text-muted">最多可上传十个附件</p> </div> </div> <input type="button" id="qr" value="上传"> <input type="button" id="cancel" value="取消"> </form> <div id="upload-div" style="margin-top: 20px"> </div> <!-- 模拟下载 --> <div> <div class="timeline-item"> <h3 class="timeline-header"><a>附件下载</a></h3> <h3 class="timeline-header"> <a href="/download/?file_path=C:\Users\tom\Desktop\updown_load\upload/00ef26ae-bd4b-11e8-80a6-d481d7cf000f.jpg&up_filename=4.jpg" class="download-file"> 附件1下载: </a> <span> 4.jpg</span> </h3> </div> </div> <script> //Dropzone Configuration Dropzone.autoDiscover = false; $(document).ready(function () { $("#filedropzone").dropzone({ url: '/upload/', maxFiles: 10, // 总共可以上传文件最大个数 maxFilesize: 200, // 上传文件最大 Mb acceptedFiles: ".jpg,.jpeg,.doc,.docx,.ppt,.pptx,.txt,.avi,.pdf,.mp3,.zip", autoProcessQueue: false, paramName: "file", dictDefaultMessage: "拖入需要上传的文件", parallelUploads: 10, // 点击上传,一次上次最大个数 dictFileTooBig:"文件过大上传文件最大支持.", init: function () { var myDropzone = this, submitButton = document.querySelector("#qr"), cancelButton = document.querySelector("#cancel"); myDropzone.on('addedfile', function (file) { //添加上传文件的过程,可再次弹出弹框,添加上传文件的信息 }); myDropzone.on('sending', function (data, xhr, formData) { //向后台发送该文件的参数 formData.append('watermark', jQuery('#info').val()); }); myDropzone.on('success', function (files, response) { //文件上传成功之后的操作 {# console.log('filex upload done...', response);#} upfile_sucess(files, response) }); myDropzone.on('error', function (files, response) { //文件上传失败后的操作 }); myDropzone.on('totaluploadprogress', function (progress, byte, bytes) { //progress为进度百分比 $("#pro").text("上传进度:" + parseInt(progress) + "%"); //计算上传速度和剩余时间 var mm = 0; var byte = 0; var tt = setInterval(function () { mm++; var byte2 = bytes; var remain; var speed; var byteKb = byte / 1024; var bytesKb = bytes / 1024; var byteMb = byte / 1024 / 1024; var bytesMb = bytes / 1024 / 1024; if (byteKb <= 1024) { speed = (parseFloat(byte2 - byte) / (1024) / mm).toFixed(2) + " KB/s"; remain = (byteKb - bytesKb) / parseFloat(speed); } else { speed = (parseFloat(byte2 - byte) / (1024 * 1024) / mm).toFixed(2) + " MB/s"; remain = (byteMb - bytesMb) / parseFloat(speed); } $("#dropz #speed").text("上传速率:" + speed); $("#dropz #time").text("剩余时间" + arrive_timer_format(parseInt(remain))); if (bytes >= byte) { clearInterval(tt); if (byteKb <= 1024) { $("#dropz #speed").text("上传速率:0 KB/s"); } else { $("#dropz #speed").text("上传速率:0 MB/s"); } $("#dropz #time").text("剩余时间:0:00:00"); } }, 1000); }); submitButton.addEventListener('click', function () { //点击上传文件 myDropzone.processQueue(); }); cancelButton.addEventListener('click', function () { //取消上传 myDropzone.removeAllFiles(); }); } }); //剩余时间格式转换: function arrive_timer_format(s) { var t; if (s > -1) { var hour = Math.floor(s / 3600); var min = Math.floor(s / 60) % 60; var sec = s % 60; var day = parseInt(hour / 24); if (day > 0) { hour = hour - 24 * day; t = day + "day " + hour + ":"; } else t = hour + ":"; if (min < 10) { t += "0"; } t += min + ":"; if (sec < 10) { t += "0"; } t += sec; } return t; } }); function upfile_sucess(files, response) { response = JSON.parse(response); var up_filename = response.up_filename; var filepath = response.filepath; // 创建div var file_div = document.createElement('div'); file_div.className = "form-group has-success has-feedback"; // 创建input var input = document.createElement('input'); input.className = "form-control up-file"; input.setAttribute("value",up_filename); input.setAttribute("filepath",filepath); input.setAttribute('disabled','disabled'); // 创建span var span = document.createElement('span'); span.className = "glyphicon glyphicon-ok form-control-feedback"; file_div.appendChild(input); file_div.appendChild(span); document.getElementById('upload-div').appendChild(file_div); } </script> </body> </html>