project classes py import logging syslog time os from django core file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# project.classes.py
import logging, syslog, time, os
from django.core.files.uploadhandler import FileUploadHandler, UploadFileException
from django.core.cache import cache
from django.conf import settings
class ProgressUploadHandler(FileUploadHandler):
"""
Download the file and store progression in the session
"""
def __init__(self, request=None, outPath="/tmp"):
super(ProgressUploadHandler, self).__init__(request)
self.progress_id = None
self.cache_key = None
self.request = request
self.outPath = outPath
self.destination = None
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
self.content_length = content_length
self.request.session['upload'] = {'uploaded': 0, 'length': self.content_length}
self.request.session.save()
def new_file(self, field_name, file_name, content_type, content_length, charset=None):
#if not is_valid_upload(file_name): # here you can use a function to filter uploaded files.
# raise UploadFileException , "forbidden file type"
self.outPath = os.path.join(self.outPath, file_name)
self.destination = open(self.outPath, 'wb+')
def receive_data_chunk(self, raw_data, start):
data = self.request.session['upload']
data['uploaded'] += self.chunk_size
self.request.session.save()
self.destination.write(raw_data)
# data wont be passed to any other handler
return None
def file_complete(self, file_size):
pass
def upload_complete(self):
try:
self.destination.close()
except:
pass
# views.py
def upload_progress(request):
"""
Return JSON object with information about the progress of an upload.
"""
data = request.session['upload']
return HttpResponse(simplejson.dumps(data))
@activation_required()
@render_to("music/upload.html")
def upload(request):
request.upload_handlers.insert(0, ProgressUploadHandler(request))
if request.POST:
form = UploadSongForm(request.POST, request.FILES)
if form.is_valid():
song = form.save()
return HttpResponseRedirect(reverse("upload-song"))
else:
form = UploadSongForm()
return {'form': form}