Uploading an image using Django and saving it into an OS file

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">
    <title>Upload image Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <h1>Upload image</h1>
        {% if form.errors %}
            <p style="color: red;">
                Please correct the error{{ form.errors|pluralize }} below.
        {% endif %}

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

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():
            return HttpResponse('Thanks for uploading the image')
            return HttpResponse('Invalid image')
        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():

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

We are Tryolabs. A boutique hi-tech company that crafts amazing Internet, Machine Learning & Mobile products.

8 thoughts on “Uploading an image using Django and saving it into an OS file

  1. Thank you man! It's what I was searching for!

    For all others, below ImageForm example:

    class ImageForm(forms.Form):
    image = forms.FileField()

Leave a Reply

Your email address will not be published. Required fields are marked *