Django-基于bootstrap文件上传,带上传进度条,完整前后台

前台
初始
Django-基于bootstrap文件上传,带上传进度条,完整前后台_第1张图片
查看文件是否上传成功
Django-基于bootstrap文件上传,带上传进度条,完整前后台_第2张图片
一、 前台
1.html设计:

2.添加js:


3.上传函数

function MyUpload(){
    var myfiles = document.getElementById("myfile").files;//获取文件
    var totalfile = myfiles.length;//上传的文件个数
    var uploadedfile = 0;//已上传的文件个数
    var data = new FormData();//构建FormData用于Ajax发送
    var file_index = 0;
    //每上传一个文件,添加一个进度条
    var addhtml = " 
文件1
\n" + "
\n" + "
上传进度:
\n" + "
100%
\n" + "
\n" + "
\n" + "
\n" + "
"; $("#show_upload").empty();//每次点击上传按钮,把所有的进度条清空 while (file_index < myfiles.length){ data.append('file', myfiles[file_index]);// 获取1个文件放入FormData中 var percentage = null;//上传进度 $.ajax({ type: "POST", url: "/FileUploads/", data: data, processData: false, // 告诉jQuery不要处理数据 contentType: false, // 告诉jQuery不要设置类型 dataType:"json", xhr:function xhr(){ var newbackname = "backname" + file_index;//文件名,本来想写后台返回的,懒 var newbackurl = "backurl" + file_index;//每个文件上传后,返回的前台访问的url var newp = "percentage" + file_index;//每个文件的进度 var newpbar = "percentagebar" + file_index;//每个进度条的名字 var myfilename = myfiles[file_index].name; $("#show_upload").append(addhtml); $("#backname").attr('id',newbackname); $("#backurl").attr('id',newbackurl); $("#percentage").attr('id',newp); $("#percentagebar").attr('id',newpbar); var myxhr = $.ajaxSettings.xhr(); if(myxhr.upload){ myxhr.upload.addEventListener('progress',function (e) { if(e.lengthComputable){ percentage = parseInt(e.loaded / e.total * 100); var now_percentage = percentage + "%"; $("#"+newp).html(now_percentage); $("#"+newpbar).css({"width":now_percentage}); $("#"+newbackname).html(myfilename); } },false); } return myxhr; }, success: function(result){ //每次上传完毕后得到返回值,取出返回的json值 var filename = result.FileName;//后台返回新的文件名 var fileurl = result.FileUrl;//后台返回的文件url uploadedfile = uploadedfile + 1; if(uploadedfile == totalfile){ $("#upload_status").text("重新上传"); alert("文件上传完毕!"); } } }); file_index = file_index + 1; } }

二、 后台
1.写url
2.写函数

@csrf_exempt
def FileUploads(req):
    file = req.FILES.get('file')  # 获取文件对象,包括文件名文件大小和文件内容
    curttime = time.strftime("%Y%m%d")
    #规定上传目录
    upload_url = os.path.join(settings.MEDIA_ROOT,'attachment',curttime)
    #判断文件夹是否存在
    folder = os.path.exists(upload_url)
    if not folder:
        os.makedirs(upload_url)
        print("创建文件夹")
    if file:
        file_name = file.name
        #判断文件是是否重名,懒得写随机函数,重名了,文件名加时间
        if os.path.exists(os.path.join(upload_url,file_name)):
            name, etx = os.path.splitext(file_name)
            addtime = time.strftime("%Y%m%d%H%M%S")
            finally_name = name + "_" + addtime + etx
            #print(name, etx, finally_name)
        else:
            finally_name = file.name
 		#文件分块上传
        upload_file_to = open(os.path.join(upload_url, finally_name), 'wb+')
        for chunk in file.chunks():
            upload_file_to.write(chunk)
        upload_file_to.close()
		#返回文件的URl
        file_upload_url = settings.MEDIA_URL + 'attachment/' + curttime + '/' +finally_name
        #构建返回值
        response_data = {}
        response_data['FileName'] = file_name
        response_data['FileUrl'] = file_upload_url
        response_json_data = json.dumps(response_data)#转化为Json格式
        return HttpResponse(response_json_data)

你可能感兴趣的:(原创,pycharm,python,formdata)