Uploading images using Django is pretty straightforward if you're using an ImageField tied to a model, but what happens if you're not working with the Django ORM, and you want to save the file directly to the OS? You'll have to deal with an "InMemoryUploadedFile" object.

Show me some code dude!

First, a simple html template to upload a file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Upload image Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <h1>Upload image</h1>
        {% if form.errors %}
            <p style="color: red;">
                Please correct the error{{ form.errors|pluralize }} below.
            </p>
        {% endif %}

		<!--malcala: please observe the enctype property below in the form header -->
        <form enctype="multipart/form-data" action="" method="post">{% csrf_token %}
            <table>
                {{ form.as_table }}
            </table>
            <input type="submit" value="Upload image">
        </form>
  </body>
</html>

Remember using the "enctype" property in the form header. Now the view and a simple helper:

def upload_image(request):
    '''Simple view method for uploading an image

    '''
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid() and form.is_multipart():
            save_file(request.FILES['image'])
            return HttpResponse('Thanks for uploading the image')
        else:
            return HttpResponse('Invalid image')
    else:
        form = ImageForm()
    return render_to_response('sample/upload_image_form.html', {'form': form})

def save_file(file, path=''):
    ''' Little helper to save a file
    ''' 
    filename = file._get_name()
    fd = open('%s/%s' % (MEDIA_ROOT, str(path) + str(filename)), 'wb')
    for chunk in file.chunks():
        fd.write(chunk)
    fd.close()

And that should do. You'll have the uploaded file saved into your MEDIA_ROOT directory.


Comments

  1. Santhosh Kumar
    Santhosh Kumar on 06/19/2012 2:37 p.m.
    Thanks. It would be much more helpful, if u upload the models.py also for this...where will i find the ImageForm ??? and where are you passing the CSRF token ?
  2. weibo
    weibo on 11/05/2012 11:26 p.m.
    it's no use today django change the file upload class
  3. mpa
    mpa on 11/26/2012 9:25 a.m.
    Didn't help at all. =/
  4. JJ
    JJ on 04/10/2013 9:54 a.m.
    Where is the ImageForm code? :(
  5. JJ
    JJ on 04/10/2013 10:02 a.m.
    This code doesn't help. I am a complete beginner. NameError at /FileUpload/ global name 'MEDIA_ROOT' is not defined
  6. Denis
    Denis on 06/05/2013 2:49 p.m.
    Thank you man! It's what I was searching for! For all others, below ImageForm example: class ImageForm(forms.Form): image = forms.FileField()
  7. Julien Le Coupanec
    Julien Le Coupanec on 11/23/2013 1:13 p.m.
    I just added a tutorial on how to upload files in AJAX with Django. Hope it will help! https://waaave.com/tutorial/django/how-to-quickly-upload-files-in-ajax-with-django-in-5-steps/
  8. bib1991
    bib1991 on 07/12/2014 2:29 a.m.
    Hi martin, Thank you for the tutorial. very useful for me

Post your comment

:

:

(Optional):

:

(Optional):