1

我正在尝试将 Uploadifive 实现到 Django 中。这对我来说很困难,因为我对 Django 不是很好。一点儿都没有。这当然应该告诉我,我应该等待并首先学习更多 Django,但是.. 是的,我将无法远离它..

据我了解,我需要看一下 Uploadifive 包附带的 PHP 脚本,并在 Django 视图中编写等效的脚本。至少这是我的猜测。问题是,我似乎无法在网上找到任何指南,或任何有关如何操作的提示。有没有人有这方面的例子,我可以看看?或者关于我应该去哪里的任何提示?

到目前为止,我已经在 urls.py 中创建了一个模式,它将浏览器定向到 view.py def,将用户发送到正确的网页。JavaScript 在现场初始化(我可以看到“选择文件”按钮),但是当我选择图像时,什么也没有发生。我尝试根据我找到的基于 Flash 的 Uploadify 指南在视图中构建一个脚本,但这不起作用。

编辑:有人指出,自然有必要看看 PHP 代码实际上做了什么。它确实是一个付费软件,但我无法想象这里的 PHP 代码会成为代码中如此重要的一部分,以至于它会“放弃”任何东西。无论如何,真正的工作在于 javascript 文件。

PHP上传收件人脚本:

<?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.';
    }
}
?>

模板:

    {% 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 %}

视图.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')
4

1 回答 1

1

这是我对 PHP 文件的 Python 翻译:

# 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.'

如果一次发送多个文件,最好将代码包装在 forloop 中:

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

然后,您显然希望返回正确的响应对象并更好地处理错误,但您应该能够自己处理。

于 2012-07-27T19:04:05.547 回答