from django shortcuts import render_to_response from django http impor

 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
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from Gallery.apps.gallery.forms import UploadFileForm
from Gallery.settings import FILE_UPLOAD_TEMP_DIR
from PIL import Image
import os
from django.core.validators import isValidImage
from cStringIO import StringIO
import time
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_origin_uploaded_file(request.FILES['img']) # img is an object from my forms class
#return HttpResponseRedirect('/success/url/') # after uploading we can redirect our user to some url
return HttpResponse('<h1>Your image success uploaded</h1>')
else:
return HttpResponse('<h1>Form is not valid, pelase try to check it </h1>')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
def handle_origin_uploaded_file(f): # Function which set new name and save file to meda folder
name_and_ext = str(f.file_name).split(".") # Split file xxxx.yy, 'coz we need file extension
extension = name_and_ext[1]
file_name = str(int(time.time())) + "." + extension # Generate timestamp for our file name
destination = open(FILE_UPLOAD_TEMP_DIR + '/'+ 'o' + file_name, 'wb')
for chunk in f.chunk():
destination.write(chunk)
resize(file_name)
def resize(file_name):
orig_path = FILE_UPLOAD_TEMP_DIR + '/' + 'o' + file_name
if os.path.isfile(orig_path):
orig_image = Image.open(orig_path)
print orig_image.format
else:
print "Fucking bastard!"
new_img = orig_image.copy()
new_img.save("/tmp/f.jpg")
def error(request):
er = "Form Is Not Valid"
return render_to_response('error.html',{'er':er})