django文件上傳下載

views:html

def mgmt_files(request): #列出樹形目錄,上傳文件頁面
    if request.method == 'POST':
        path_root = "D:\\py\\ITFiles" #上傳文件的主目錄
        myFile =request.FILES.get("file", None)    # 獲取上傳的文件,若是沒有文件,則默認爲None  
        if not myFile:  
            dstatus = "請選擇須要上傳的文件!"
        else:
            path_ostype = os.path.join(path_root,request.POST.get("ostype"))
            path_dst_file = os.path.join(path_ostype,myFile.name)
            # print path_dst_file
            if os.path.isfile(path_dst_file):
                dstatus = "%s 已存在!"%(myFile.name)
            else:
                destination = open(path_dst_file,'wb+')    # 打開特定的文件進行二進制的寫操做  
                for chunk in myFile.chunks():      # 分塊寫入文件  
                    destination.write(chunk)  
                destination.close()  
                dstatus = "%s 上傳成功!"%(myFile.name)
        return HttpResponse(str(dstatus))

    return render(request,'sinfors/mgmt_files.html')


def mgmt_file_download(request,*args,**kwargs): #提供文件下載頁面
    #定義文件分塊下載函數 
    def file_iterator(file_name, chunk_size=512):
        with open(file_name,'rb') as f: #若是不加‘rb’以二進制方式打開,文件流中遇到特殊字符會終止下載,下載下來的文件不完整 while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    path_root = "D:\\py\\ITFiles"
    if kwargs['fpath'] is not None and kwargs['fname'] is not None:
        file_fpath = os.path.join(path_root,kwargs['fpath']) #kwargs['fapth']是文件的上一級目錄名稱
        file_dstpath = os.path.join(file_fpath,kwargs['fname']) #kwargs['fname']是文件名稱

        response = StreamingHttpResponse(file_iterator(file_dstpath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(kwargs['fname']) #此處kwargs['fname']是要下載的文件的文件名稱 return response

  StreamingHttpResponse對象用於將文件流發送給瀏覽器,與HttpResponse對象很是類似,對於文件下載功能,使用StreamingHttpResponse對象更合理。經過文件流傳輸到瀏覽器,但文件流一般會以亂碼形式顯示到瀏覽器中,而非下載到硬盤上,所以,還要在作點優化,讓文件流寫入硬盤,給StreamingHttpResponse對象的Content-Type和Content-Disposition字段賦下面的值便可,如:ajax

response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="filename.txt"'瀏覽器

 

 

html頁面:app

 <form id="uploadForm" enctype="multipart/form-data"> //文件上傳的form
            {% csrf_token %}
            <input id="file" type="file" name="file" > //上傳文件
            <input type="radio" name="ostype" value="Windows" />Windows 
            <input type="radio" name="ostype" value="Linux" />Linux
            <input type="radio" name="ostype" value="Network" />Network
            <input type="radio" name="ostype" value="DB" />DB
            <button id="upload" type="button" style="margin:20px">上傳</button>
</form>

js頁面:函數

  $("#upload").click(function(){
    // alert(new FormData($('#uploadForm')[0]));
    var ostype = $('input:radio:checked').val()
    if (ostype == undefined){
      alert('請選擇上傳的文件類型');
    }
     //獲取單選按鈕的值
    $.ajax({
            type: 'POST',
            // data:$('#uploadForm').serialize(),
            data:new FormData($('#uploadForm')[0]),
            processData : false,   
            contentType : false, //必須false纔會自動加上正確的Content-Type  
            // cache: false,
            success:function(response,stutas,xhr){
              // parent.location.reload();
              //window.location.reload();
              // alert(stutas);
              alert(response);
            },
            // error:function(xhr,errorText,errorStatus){
            //   alert(xhr.status+' error: '+xhr.statusText);
            // }
            timeout:6000
        });

  });

相關文章
相關標籤/搜索