Sunday, May 4, 2014

File upload

One of the most common functions your website should be able to do is to upload/download pictures, PDFs and other files. In this tutorial I will show you how to create an upload script and save the files to server.
If you recall, I already showed you how to host your site on a free server. Now there are two parts to uploading files:

  1. Creating an upload script post which the file gets stored on either the server or temporary storage on your computer depending on which has more space.
  2. Copying the file from temporary storage to a permanent destination.
Let's take care of this in two parts.

Part I: Creating an upload script
Ok, first we need to create an HTML form. In a file called upload.html, type the following code.

<form action = "/uploaded/" method = "post" enctype="multipart/form-data">
Select an image: <input type = "file" name = "img"><br><br>
<input type = "submit" name = "upload" value = "Upload picture">
</form>

The enctype="multipart/form-data" is extremely important, as it specifies the encryption type of the temp file. With this done, when the 'upload' button is pressed, the file gets stored on temp storage. To render the upload page, write a simple view.

def upload (request):
    return render (request, "upload.html")

The view that we need to write for uploaded is important. But that is in part two.

Part II: Copying file to permanent storage
Now that we have the file, let's copy it to the server. We'll do this in the uploaded view.

def uploaded (request):
  file = request.FILES['img']
  dest = open ("/foo/bar/image_name.jpeg", "w")
for bit in file.read ():
dest.write (bit)
return HttpResponse ("Uploaded")

Note that the extensions of both the files should be same. We can access the temp file through request.FILES. We're reading each unit of the temp file and putting it into our permanent one.
Easy enough, right?
Don't forget to add the URLs in ulrs.py

url (r'^upload/', 'myproject.myapp.views.upload'),
url(r'^uploaded/', 'myproject.myapp.views.uploaded'),

Cheers!

No comments:

Post a Comment