1 # Create your views here. |
1 #can add features like: supporting files with specified extensions, making edit box of content better etc. |
|
2 from django.http import HttpResponse |
|
3 from django.template import Context, Template |
|
4 from django.shortcuts import render_to_response |
|
5 from form import FileForm, Uploaded_fileForm |
|
6 import tarfile |
|
7 |
|
8 #function to read the upoaded file and store it |
|
9 def handle_uploaded_file(f): |
|
10 destination = open(f.name, 'wb+') |
|
11 for chunk in f.chunks(): |
|
12 destination.write(chunk) |
|
13 destination.close() |
|
14 |
|
15 #view to handle uploaded file, showing content of file, and option of uploading a file |
|
16 def upload_file(request,template_name='index.html'): |
|
17 if request.method == 'POST': |
|
18 form = FileForm(request.POST, request.FILES) |
|
19 if form.is_valid(): |
|
20 #if else for checking the size of uploaded file |
|
21 handle_uploaded_file(request.FILES['file']) |
|
22 uploaded_form = Uploaded_fileForm(initial={'content': open(request.FILES['file'].name).read()}) |
|
23 c = Context({'form': uploaded_form, |
|
24 'value': False, |
|
25 }) |
|
26 #display a page with textbox and all the content of file |
|
27 return render_to_response(template_name, |
|
28 context_instance = c) |
|
29 c = Context({'form': FileForm(), |
|
30 'value': True, |
|
31 }) |
|
32 return render_to_response(template_name, |
|
33 context_instance = c) |
|
34 |
|
35 #to create the dump of content shown in text box and then making it downloadable |
|
36 def file_archive(request): |
|
37 if request.method == 'POST': |
|
38 form = Uploaded_fileForm(request.POST, request.FILES) |
|
39 if form.is_valid(): |
|
40 response = HttpResponse(mimetype='application/tar') |
|
41 response['Content-Disposition'] = 'attachment; filename=content.tar' |
|
42 content = open('download.txt','w') |
|
43 content.write(form.cleaned_data['content']) |
|
44 content.close() |
|
45 tar = tarfile.open('download.tar','w') |
|
46 tar.add('download.txt') |
|
47 tar.close() |
|
48 response.write(open('download.tar').read()) |
|
49 return response |
|
50 return HttpResponseRedirect('/ocr/') |
|
51 |