1

I am trying to implement Uploadifive into Django. It's proving difficult for me since I'm not very good with Django. Not even a little bit. This of course should tell me that I should wait with this and learn more Django first, but.. Yeah, I won't be able to stay away from it..

As far as I've understood, I need to take a look at the PHP-script that comes with the Uploadifive package and write the equivalent of that in a Django view. That's my guess at least.. Problem is, I can't seem to find any guides online, or any tips on how to do it. Does anyone out there have an example of this that I could take a look at? Or any tips on where I should go?

So far I have created a pattern in urls.py that directs a browser to a views.py def that sends the user to the right web page. The JavaScript initializes on site (as I can see the "Select Files" button), but when I select images, nothing happens. I've tried to build a script in view based on the flash-based Uploadify guides I have found, but this doesn't work.

EDIT: It was pointed out that it was naturally necessary to see what the PHP-code actually did as well. It is indeed a paid software, but I cannot imagine the PHP-code here to be such a big part of the code that it would "give away" anything. The real work lies in the javascript files anyway.

PHP upload recipient script:

<?php
/*
UploadiFive
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
*/

// Set the uplaod directory
$uploadDir = '/uploads/';

// Set the allowed file extensions
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions

if (!empty($_FILES)) {
    $tempFile   = $_FILES['Filedata']['tmp_name'];
    $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
    $targetFile = $uploadDir . $_FILES['Filedata']['name'];

    // Validate the filetype
    $fileParts = pathinfo($_FILES['Filedata']['name']);
    if (in_array(strtolower($fileParts['extension']), $fileTypes)) {

        // Save the file
        move_uploaded_file($tempFile,$targetFile);
        echo 1;
    } else {
        // The file type wasn't allowed
        echo 'Invalid file type.';
    }
}
?>

Template:

    {% extends 'base/index.html' %}
    {% block stylesheet %}
      <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}uploadifive/uploadifive.css">
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
      <script type="text/javascript" src="{{ STATIC_URL }}uploadifive/jquery.uploadifive.js"></script>
      <script type="text/javascript">
      $(document).ready(function(){
        $('#file_upload').uploadifive({
          'debug': true,
          'formData':{'test':'something'},
          'uploadScript': '/upload/',
          'queueID': 'queue',
          'cancelImage': '{{ STATIC_URL }}uploadifive/uploadifive-cancel.png',
          'auto': true
        });
      });
      </script>
    {% endblock %}

    {% block content %}
      <form>
        <input type="file" name="file_upload" id="file_upload" />
      </form>
    {% endblock %}

views.py

    from django.shortcuts import render
    from gallery.models import Pic,Comment,Tag
    from django.conf import settings
    from django.http import HttpResponse
    from django.shortcuts import render

    def upload(request):
        if request.method == 'POST':
            for field_name in request.FILES:
                uploaded_file = request.FILES[field_name]

                #write the file into destination
                destination_path = '<absolute path to project>/media/gallery/pictures/%s' % (uploaded_file.name)
                destination = open(destination_path, 'wb+')
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
                destination.close()

            #indicate that everything is OK
            return HttpResponse("ok", mimetype="text/plain")
        else:
            #show the upload UI
            return render(request, 'gallery/upload.html')
2
  • The problem is that this is a paid package, so it makes it hard to tell you how to translate the PHP properly to Python if we can't see the actual PHP code. Sorry, I'm not paying $5 to help you ;). You can check the license you have and see if perhaps it might allow you to post the script here, or maybe even a partial bit that might be enough to get you started. Otherwise, I'd complain to the developer that they should add Python support. Jul 27, 2012 at 14:31
  • @ChrisPratt - You are of course correct. I edited the question and input the PHP-bit as well now. Like I wrote in the question; the PHP-bit is so small and kind of basic really. The real magic of the purchased sofware lies in the JavaScript.
    – Geir K.H.
    Jul 27, 2012 at 18:47

1 Answer 1

1

Here's my Python translation of the PHP file:

# Set the uplaod directory
upload_dir = '/absolute/path/to/upload/dir/'

# Set the allowed file extensions
file_types = ['jpg', 'jpeg', 'gif', 'png'] # Allowed file extensions

if len(request.FILES):
    target_file = upload_dir + request.FILES['field_name'].name

    # Validate the filetype
    filename, ext = os.path.splitext(request.FILES['field_name'].name)
    if ext.lower() in file_types:

        # Save the file
        with open(target_file, 'wb+') as destination:
            for chunk in request.FILES['field_name'].chunks():
                destination.write(chunk)
    else:
        # The file type wasn't allowed
        print 'Invalid file type.'

If there's multiple files being sent at once, it would probably be better to just wrap the code in a forloop:

for file in request.FILES.values():
    target_file = upload_dir + file.name
    ...

Then, you obviously want to return proper response objects and handle errors better, but you should be able to handle that on your own.

1
  • Thank you very much for this :) I tried to input this and ran it. It doesn't seem to raise any errors, but it still doesn't seem to do anything either. I tried inputing some prints here and there to see if anything came out of it, but it didn't. It's almost as if the view doesn't launch at all. Unless I'm looking for the prints in the completely wrong place of course, which is not at all impossible..
    – Geir K.H.
    Jul 27, 2012 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.