1

Uploadifive を Django に実装しようとしています。私は Django があまり得意ではないので、難しいことがわかりました。少しでもありません。もちろん、これは私がこれで待って、最初に Django をもっと学ぶべきだと教えてくれるはずですが..ええ、私はそれから離れることはできません..

私が理解している限りでは、Uploadifive パッケージに付属している PHP スクリプトを調べて、Django ビューでそれと同等のものを記述する必要があります。それは少なくとも私の推測です..問題は、オンラインでガイドやその方法に関するヒントが見つからないように見えることです。誰かが私が見ることができるこの例を持っていますか? または、どこに行くべきかについてのヒントはありますか?

これまでのところ、urls.py にパターンを作成し、ブラウザを views.py 定義に誘導して、ユーザーを正しい Web ページに送りました。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 に答える