Skip to content Skip to sidebar Skip to footer

Using Javascript And Django To Upload A Text File To Some Folder In Server

I need to upload a text file which contains some data ,from my local filesystem to say {{MEDIA_URL}}/uploadfolder.This file is to be processed by one of the functions in my django

Solution 1:

Before I get into any javascript, first you should understand how files are generally uploaded and handled using Django. Consider the following html form:

<form method="post" action="/foo/url/">
    <input type="file" name="foofile">
    <input type="submit" value="Upload">
</form>

So when the user clicks submit button, the browser will upload that file to the /foo/url/ using HTTP method POST. Then on the server side in Django, the url /foo/url/ will be mapped to some view. In your case it will be storeAndProcessFile. So what the view will have to do is take the file which was uploaded and store that to disk (or possibly some other storage system).

Now the view does not get the file as one of its function parameters like you showed in your question. That is because how GET, POST, and FILE data is passed in HTTP requests. So the file will actually be a part of the request parameter inside the view. You would be able to reference the file by request.FILES['foofile'].

To just store the file to disk, your view might look something like:

def storeAndProcessFile(request):
    # make sure the the request method is POST
    if request.method != 'POST':
        return HttpResponseBadRequest('Only POST requests are allowed')
    # now get the uploaded file
    file = request.FILES['foofile']
    # the file is going to be an instance of UploadedFile
    with open('/destination/path/%s' % file.name, 'wb+') as dest:
        for chunk in file.chunks():
            dest.write(chunk)
    # return success message
    return HttpResponse('File uploaded')

This code is pretty much out of Django documentation. If you want to know more, you can read it here.

As for Javascript, there are ton of jQuery plugins where can upload files using ajax or even multiple files at once. I really like this library. It has many features including sending multiple files. However if that is too much you can just do a search for jQuery file upload plugin and there are ton of them but I haven't tested any others recently so can't give any recommendation.

There is however one thing to bear in mind when making ajax requests to a Django site, which is CSRF. Since Django 1.2.5 they changed how CSRF is validated and that can break many upload libraries. If you don't need to worry about it, you can always add csrf_exempt decorator:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def storeAndProcessFile(request):
    ...

If however you need CSRF, you can take a look at sample implementation of integrating jQuery file uploader with CSRF enabled here.


Post a Comment for "Using Javascript And Django To Upload A Text File To Some Folder In Server"