python+django+javascript+layer単純小demoファイルアップロード

3442 ワード

上の簡単なブログで説明した後、今日はフロントエンドとバックエンドのコードを大まかにします.大まかなコードは次のとおりです.
{#   form  enctype="multipart/form-data"  #}

 
  // 
    function transferBtn(cur){
      var form = document.getElementById('upload'),
      formData = new FormData(form);
      $.ajax({
       url:"{% url 'upload' %} ",
       type:"post",
       data:formData,
       processData:false,
       contentType:false,
       success:function(data){
            if(data == 'ok'){
                layer.msg(" !");
            }
            if(data == 'exists'){
                // 
            layer.confirm(' , ?', {
                btn: [' ', ' '],
            }, // 
            function () {
                coverFile();
            },
            function () {
                layer.msg(' ');
            });
            }
      }

    })
    }
    // 
    function coverFile() {
        var form = document.getElementById('upload');
        $("#coverFile").val('True');
        formData = new FormData(form);
        $.ajax({
           url:"{% url 'upload' %} ",
           type:"post",
           data:formData,
           processData:false,
           contentType:false,
           success:function(data){
               layer.msg(' ');
           }
        })
    }

 
def upload(request):
    if request.method == "POST":
        company = request.POST.get("companyF")
        file = request.FILES.get('img')      #  
        coverFile = request.POST.get("coverFile")

        file_name = file.name
        path = tools.DOC_BASE_DIR + request.user.username + '/' + company + '/'
        all_path = path + file_name
        if os.path.exists(path) is False:
            os.makedirs(path)

        if os.path.exists(all_path) and coverFile == 'False':
            return HttpResponse('exists')
        with open(all_path, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        return HttpResponse("ok")

    # return render(request, 'report_template.html')

 
def fileExistsOrNot(request):
    company_name = request.POST.get("company_name")
    file_name = request.POST.get("file_name")
    path = tools.DOC_BASE_DIR + request.user.username + '/' + company_name + '/' + file_name

    if os.path.exists(path):
        return HttpResponse(" ")
    else:
        return HttpResponse("OK")