文件上传、下载

文件上传、文件展示、文件删除、文件下载

models.py:

class KnowledgeFileDownload(models.Model):
    person = models.CharField("上传人", blank=True, null=True, max_length=64)
    upload_time = models.DateTimeField("上传时间", blank=True, null=True)
    remark = models.CharField("备注", blank=True, null=True, max_length=500)
    file_name = models.CharField("文件名称", blank=True, null=True, max_length=128)
    state = models.CharField("状态", blank=True, null=True, max_length=20)

urls.py:

url(r'^downloadlist/$', downloadlist, {'funid': '7'}),
url(r'^download/$', download),
url(r'^download_list_data/$', download_list_data),
url(r'^knowledge_file_del/$', knowledge_file_del),

views.py:

# 上传
def downloadlist(request, funid):
    if request.user.is_authenticated():
        errors = []
        if request.method == 'POST':
            file_remark = request.POST.get("file_remark", "")
            my_file = request.FILES.get("myfile", None)
            if not my_file:
                errors.append("请选择要导入的文件。")
            else:
                if if_contains_sign(my_file.name):
                    errors.append(r"""请注意文件命名格式,'\/"*?<>'符号文件不允许上传。""")
                else:
                    myfilepath = settings.BASE_DIR + os.sep + "drm" + os.sep + "upload" + os.sep + "knowledgefiles" + os.sep + my_file.name

                    c_exist_model = KnowledgeFileDownload.objects.filter(file_name=my_file.name).exclude(state="9")

                    if os.path.exists(myfilepath) or c_exist_model.exists():
                        errors.append("该文件已存在,请勿重复上传。")
                    else:
                        with open(myfilepath, 'wb+') as f:
                            for chunk in my_file.chunks():  # 分块写入文件
                                f.write(chunk)

                        # 存入字段:备注,上传时间,上传人
                        c_file = KnowledgeFileDownload()
                        c_file.file_name = my_file.name
                        c_file.person = request.user.userinfo.fullname
                        c_file.remark = file_remark
                        c_file.upload_time = datetime.datetime.now()
                        c_file.save()

                        errors.append("导入成功。")
        return render(request, "downloadlist.html",
                      {'username': request.user.userinfo.fullname, "errors": errors,
                       "pagefuns": getpagefuns(funid, request=request)})
    else:
        return HttpResponseRedirect("/login")

# 展示
def download_list_data(request):
    if request.user.is_authenticated():
        result = []
        c_files = KnowledgeFileDownload.objects.exclude(state="9")
        if c_files.exists():
            for file in c_files:
                result.append({
                    "id": file.id,
                    "name": file.person,
                    "up_time": "{0:%Y-%m-%d %H:%M:%S}".format(file.upload_time),
                    "remark": file.remark,
                    "file_name": file.file_name,
                })

        return JsonResponse({
            "data": result
        })

# 删除
def knowledge_file_del(request):
    if request.user.is_authenticated():
        file_id = request.POST.get("id", "")
        assert int(file_id), "网页异常"

        c_file = KnowledgeFileDownload.objects.filter(id=file_id)
        if c_file.exists():
            c_file = c_file[0]
            c_file.delete()
            c_file_name = c_file.file_name
            the_file_name = settings.BASE_DIR + os.sep + "drm" + os.sep + "upload" + os.sep + "knowledgefiles" + os.sep + c_file_name
            if os.path.exists(the_file_name):
                os.remove(the_file_name)
            result = "删除成功。"
        else:
            result = "文件不存在,删除失败,请于管理员联系。"

        return JsonResponse({
            "data": result
        })

# 下载
def download(request):
    if request.user.is_authenticated():
        file_id = request.GET.get("file_id", "")
        assert int(file_id), "网页异常"
        c_file = KnowledgeFileDownload.objects.filter(id=file_id)
        if c_file.exists():
            c_file = c_file[0]
            c_file_name = c_file.file_name
        else:
            raise Http404()
        try:
            the_file_name = settings.BASE_DIR + os.sep + "drm" + os.sep + "upload" + os.sep + "knowledgefiles" + os.sep + c_file_name
            response = StreamingHttpResponse(file_iterator(the_file_name))
            response['Content-Type'] = 'application/octet-stream; charset=unicode'
            response['Content-Disposition'] = 'attachment;filename="{0}"'.format(
                escape_uri_path(c_file_name))  # escape_uri_path()解决中文名文件
            return response
        except:
            return HttpResponseRedirect("/downloadlist")
    else:
        return HttpResponseRedirect("/login")

downloadlist.html:

    <table class="table table-striped table-bordered table-hover table-checkable order-column" id="sample_1">
        <thead>
        <tr>
            <th style="width:40px;"> 序号</th>
            <th> 上传人</th>
            <th> 上传时间</th>
            <th> 备注</th>
            <th> 文件名</th>
            <th style="width:50px;"> 操作</th>
        </tr>
        </thead>

        <tbody>

        </tbody>
    </table>
  
  
    <div id="static1" class="modal fade" tabindex="-1" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                    <h4 class="modal-title">上传</h4>
                </div>
                <div class="panel-body">
                    <form action="" enctype="multipart/form-data" class="form-horizontal"
                          method="post">{% csrf_token %}
                        <div class="form-body">
                            <div class="form-group">
                                <label class="col-md-2 control-label"><span
                                        style="color:red; "></span>文件</label>
                                <div class="col-md-10">
                                    <div class="fileinput fileinput-new" data-provides="fileinput">
                                        <div class="input-group input-large">
                                            <div class="form-control uneditable-input input-fixed input-medium"
                                                 data-trigger="fileinput">
                                                <i class="fa fa-file fileinput-exists"></i>&nbsp;
                                                <span class="fileinput-filename"> </span>
                                            </div>
                                            <span class="input-group-addon btn default btn-file">
                                                <span class="fileinput-new"> 选择文件 </span>
                                                <span class="fileinput-exists"> 重新选择 </span>
                                                <input type="file" name="myfile">
                                            </span>
                                            <a href="javascript:;" class="input-group-addon btn red fileinput-exists"
                                               data-dismiss="fileinput"> 移除 </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-md-2 control-label"><span
                                        style="color:red; "></span>备注</label>
                                <div class="col-md-10">
                                    <input id="file_remark" type="text" name="file_remark" class="form-control "
                                           placeholder="">
                                    <div class="form-control-focus"></div>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions ">
                            <div class="modal-footer">
                                <button type="submit" id="upload" name="upload" class="btn green uppercase">上传</button>
                                <button type="button" data-dismiss="modal" class="btn dark btn-outline">关闭
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>


    <link href="/static/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css"/>
    <link href="/static/assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css"/>
    <link href="/static/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="/static/assets/global/css/components.css" rel="stylesheet" id="style_components" type="text/css"/>
    <link href="/static/assets/global/css/plugins.css" rel="stylesheet" type="text/css"/>
    <script src="/static/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
    <script src="/static/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
    <script src="/static/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.js" type="text/javascript"></script>

 downloadlist.js:

$('#sample_1').dataTable({
    "bAutoWidth": true,
    "bSort": false,
    "bProcessing": true,
    "ajax": "../download_list_data/",
    "columns": [
        {"data": "id"},
        {"data": "name"},
        {"data": "up_time"},
        {"data": "remark"},
        {"data": "file_name"},
        {"data": null}
    ],

    "columnDefs": [{
        "targets": -1,  // 指定最后一列添加按钮;
        "data": null,
        "width": "60px",  // 指定列宽;
        "render": function (data, type, full) {
            return "<td><button class='btn btn-xs btn-primary' type='button'><a href='/download/?file_id'><i class='fa fa-arrow-circle-down' style='color: white'></i></a></button>" +
                "<button title='删除'  id='delrow' class='btn btn-xs btn-primary' type='button'><i class='fa fa-trash-o'></i></button></td>".replace("file_id", "file_id=" + full.id)
        }
    }],
    "oLanguage": {
        "sLengthMenu": "每页显示 _MENU_ 条记录",
        "sZeroRecords": "抱歉, 没有找到",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "sInfoEmpty": "没有数据",
        "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
        "sSearch": "搜索",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "前一页",
            "sNext": "后一页",
            "sLast": "尾页"
        },
        "sZeroRecords": "没有检索到数据",
    }
});
// 删除 $('#sample_1 tbody').on('click', 'button#delrow', function () { if (confirm("确定要删除该条数据?")) { var table = $('#sample_1').DataTable(); var data = table.row($(this).parents('tr')).data(); $.ajax({ type: "POST", url: "../knowledge_file_del/", data: { id: data.id, }, success: function (data) { if (data.data === "删除成功。") { table.ajax.reload(); alert(data.data); } else alert(data.data); }, error: function (e) { alert("删除失败,请于管理员联系。"); } }); } }); // 新增 $("#new").click(function () { $("#file_remark").val(""); });

上传:

下载:

 

posted @ 2021-01-21 22:58  TianShu  Views(85)  Comments(0Edit  收藏  举报