django 파일 업로드 진행률 표시줄

2960 단어 django
upload.html




	
	Document
	
		function on_progress(evt) {       //         upload  。          evt(event)  (      progress),  3   lengthComputable,loaded,total,       bool   ,      ,            ,        ,                
			if(evt.lengthComputable) {
				var ele = document.getElementById('2');
				var percent = Math.round((evt.loaded) * 100 / evt.total);
				ele.style.width = percent + '%';
				document.getElementById('3').innerHTML = percent + '%';
			}
		}
		function upload() {
			var xhr = new XMLHttpRequest();
			var file = document.getElementById('file').files[0];   //      , .file        
            console.log(file);
			var form = new FormData();   //FormData HTML5             ,         
            form.append('file',file);   //          form      , file
			xhr.upload.addEventListener('progress',on_progress,false);     //xhr      upload  ,    progress  ,              ,               ,              ,                 ,         
			xhr.open('POST','http://127.0.0.1/load/upload/',true);  //  url    url
            xhr.setRequestHeader('X-CSRFTOKEN','{{ request.COOKIES.csrftoken }}');   //   Django  ,   ,            CSRF  ,  django     
			xhr.send(form);   //    
		}
	


	
{% csrf_token %}
0%

view.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,HttpResponse
from django.views.generic import View

# Create your views here.
class UploadPage(View):
    def get(self,request):
        return render(request,'upload.html')

class Upload(View):
    def post(self,request):
        file = request.FILES['file']
        self.handle_uploaded_file(file)
        return HttpResponse()

    def handle_uploaded_file(self,f):
        with open(r'C:\\Users\\Desktop\\modeluser\\upload_file.txt', 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)
from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^load/', include('books.urls')),
]
from django.conf.urls import url,include
from views import *

urlpatterns = [
    url(r'upload_page/', UploadPage.as_view()),
    url(r'upload/', Upload.as_view()),
]

 
 
참조:https://blog.csdn.net/AC_hell/article/details/52832027
https://www.jb51.net/article/140988.htm

좋은 웹페이지 즐겨찾기