Login

Image uploader to use with file uploader from http://github.com/valums/file-uploader

Author:
tgdn
Posted:
January 6, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Upload an image with file-uploader from http://github.com/valums/file-uploader and save it to disk with the snippet and also to database if you want to

 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
"""
Created on Jan 7, 2012

@author: tgdn <tgdn45[AT]gmail[DOT]com>
"""


import json

def upload(request):
  """
  This snippet should be used with javascript file-uploader
  from Andrew Valums ( andrew(at)valums.com ) http://github.com/valums/file-uploader
  """
  
  # should be an ajax request
  if request.is_ajax():
    # Get image from raw data
    image = request.raw_post_data
    
    # The original filename
    name = request.GET.get('qqfile', 'some_name')
    
    # Where to upload the file
    url = '%s/uploads/%s' % (settings.MEDIA_ROOT, name)
    
    # Writing image to 'url' directory
    destination = open(url, 'wb+')
    destination.write(image)
    destination.close()
    
    """
    If you want to save the image in a database do like this:
    (according that 'Image' is the image model)
    *models.py*
    
    from django.db import models
    
    class Image(models.Model):
      image = models.ImageField(upload_to='uploads')
    
    ---
    
    And right after the image writing above:
    
    image = Image(image="uploads/%s" % name)
    image.save()
    
    """
    
    output = {
      'success': True
    }
    
    return HttpResponse(json.dumps(output))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.