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">
<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.

We are Tryolabs. A boutique hi-tech company that creates amazing Internet & 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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>