Django+layui 实现多文件上传,文件下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SilentWu/article/details/90179949

Django+layui 实现多文件上传、文件下载

django教程:http://www.liujiangblog.com/course/django/84

                      https://www.runoob.com/django/django-tutorial.html

layui官网:       https://www.layui.com/doc/

layui样式调整:http://www.hangge.com/blog/cache/detail_2078.html

多文件上传

效果:

主要代码(路由配置的就不展现了):前端

 <form class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 56px;padding-left: 0">所属类型</label>
            <div class="layui-input-block">
                <select name="resource_type">
                    <option value=""></option>
                    <option value="教育资源">教育资源</option>
                    <option value="专业资料">专业资料</option>
                    <option value="IT资料">IT资料</option>
                    <option value="娱乐生活">娱乐生活</option>
                    <option value="经济管理">经济管理</option>
                    <option value="办公文书">办公文书</option>

                </select>
            </div>
        </div>


    </form>
     <br/>
    <div class="layui-upload">
        <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>大小</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="demoList"></tbody>
            </table>
        </div>
        <button type="button" class="layui-btn" id="testListAction">开始上传</button>
    </div>
</div>

<script type="text/javascript" src="../../../static/layui/layui.js"></script>

<script>
    var form;
    var files;

    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;


        //多文件列表示例
        var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#testList'
            , method: 'POST'
            , accept: 'file'
            , multiple: true
            , auto: false
            , choose: function (obj) {

                files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                    getFileNames();//得到文件名
                });
            }
            , done: function (res, index, upload) {
                if (res.code == 0) { //上传成功
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

    });

    function getFileNames() {
        var count = 0;
        form = new FormData();
        // form.append("file", files[0]);
        // 将文件列表加入FormData()中
        for (let i in files) {
            form.append("file" + count, files[i]);
            console.log("--------" + i + "---->" + files[i]);
            count = count + 1;
        }
        // 获得上传的文件总数
        form.append("files_count", count);
        // 获得上传的文件类型
        form.append("resource_type", $("select[name='resource_type']").val());


    }


    $(document).ready(function () {
        $("#test").click(function () {
            alert($("select[name='resource_type']").val())
        });
        $("#testListAction").click(function () {
            $.ajax({
                url: "upload_resource_process",
                type: "POST",
                async: true,// 异步上传
                data: form,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                success: function (data) {
                    var demoListView = $('#demoList');
                    demoListView.empty();
                    // 每次上传成功后将文件列表清空
                    for (let i in files) {
                        delete files[i];
                    }
                    layer.msg('上传成功', {
                        icon: 6
                    });
                },
                error: function () {
                    alert("error");
                }
            })

        });
    });
</script>

后端:

def upload_resource_process(request):
    user = request.session.get('user', None)
    # 用户如果没有登录 跳转到登录界面
    if not user:
        return redirect('/user/login')
    notice_five = models.Notice.objects.filter(Q(user=user) & Q(notice_status='未读')).count()
    files_count = request.POST['files_count']
    resource_type = request.POST['resource_type']
    print('file_count---------->%s' % files_count)
    now = datetime.datetime.now() # 得到当前时间
    for i in range(int(files_count)):
        resource_file = request.FILES['file' + str(i)]
        # 保存至数据库中
        resource = Resource(
            user=user,
            resource_type=resource_type,
            resource_name=resource_file,
            resource_file=resource_file,
            resource_status='待审核',
            submit_time=now,

        )
        resource.save()
        print(resource_file)
    print('*' * 50)

    print("uploading--------------------------------------------")
    return render(request, "resource_manage/upload_resource.html",
                  {"notices": notice_five, "user": user})

文件下载

效果:

主要代码:前端

  <table class="layui-table" lay-even="" lay-skin="nob">
                            <colgroup>
                                <col width="260">
                                <col width="200">
                                <col width="200">
                                <col width="200">
                                <col width="200">
                                <col>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>文件名</th>
                                <th>文件类型</th>
                                <th>状态</th>
                                <th>上传时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                        <!-- 得到用户所有的资源列表 -->
                            {% for resource in other_resource %}
                                <tr>
                                    <td>
<!-- 通过超链接下载资源 -->
                                        <a href="download_resource?file_name={{ resource.resource_name }}">{{ resource.resource_name }}</a>
                                    </td>
                                    <td>{{ resource.resource_type }}</td>
                                    <td>{{ resource.resource_status }}</td>
                                    <td>{{ resource.submit_time|date:"Y/n/j" }}
                                        &nbsp;&nbsp;&nbsp;{{ resource.submit_time|time|cut:"." }}</td>
                                    <td>
                                        <button class="layui-btn layui-btn-danger layui-btn-xs"
                                                resource_id="{{ resource.id }}"
                                                name="delete_resource">删除
                                        </button>
                                    </td>
                                </tr>
                            {% endfor %}

                            </tbody>
                        </table>

后端:

from django.http import HttpResponse,StreamingHttpResponse
# 下载资源
def download_resource(request):
    # do something
    the_file_name = request.GET['file_name']
    # 显示在弹出对话框中的默认的下载文件名
    print('the_file_name--------->' + the_file_name)
    filename = 'media/resource/' + the_file_name  # 要下载的文件路径
    print('filename--------------->' + filename)

    response = StreamingHttpResponse(readFile(filename))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
    return response


def readFile(filename, chunk_size=512):
    with open(filename, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break

猜你喜欢

转载自blog.csdn.net/SilentWu/article/details/90179949