Django - Ajax - Uploader Model:保存文件

时间:2015-01-22 19:05:56

标签: jquery python ajax django file-upload

我正在尝试创建一个django-ajax-uploader来创建模型。我已经创建了一个示例,但我无法理解是否需要使用import_uploader或创建一个简单的类来保存带有文件的模型。如果我这样做,我也不知道AJAX动作是否会被禁用。

urls.py

from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'bft.views.home', name='home'),
    # url(r'^bft/', include('bft.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'start$', 'bbb.views.start', name="start"),
    url(r'ajax-upload$', 'bbb.views.import_uploader', name="my_ajax_upload"),
)

views.py

from django.middleware.csrf import get_token
from django.shortcuts import render_to_response
from django.template import RequestContext
from ajaxuploader.views import AjaxFileUploader

def start(request):
    csrf_token = get_token(request)
    return render_to_response('import.html',
        {'csrf_token': csrf_token}, context_instance = RequestContext(request))

import_uploader = AjaxFileUploader()
# Create your views here.

import.html

 <!doctype html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
            <script src="{{ STATIC_URL }}ajaxuploader/js/fileuploader.js" ></script>
            <link href="{{ STATIC_URL }}ajaxuploader/css/fileuploader.css" media="screen" rel="stylesheet" type="text/c$
            <script>
                $(function(){
                var uploader = new qq.FileUploader({
                    action: "/ajax-upload",
                    element: $('#file-uploader')[0],
                    multiple: true,
                    onComplete: function(id, fileName, responseJSON) {
                        if(responseJSON.success) {
                            alert("success!");
                        } else {
                            alert("upload failed!");
                        }
                    },
                    onAllComplete: function(uploads) {
                        // uploads is an array of maps
                        // the maps look like this: {file: FileObject, response: JSONServerResponse}
                        alert("All complete!");
                    },
                    params: {
                        'csrf_token': '{{ csrf_token }}',
                        'csrf_name': 'csrfmiddlewaretoken',
                        'csrf_xname': 'X-CSRFToken',
                    },
                });
                });
            </script>
        </head>
    <body>
        <div id="file-uploader">
            <noscript>
                <p>Please enable JavaScript to use file uploader.</p>
            </noscript>
        </div>
    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

包中提供的信号功能就是答案,谢谢!。

答案 1 :(得分:0)

首先,我建议您使用模型FILEFIELD创建一个模型来存储信息和文件的URL:

设置媒体文件,文件将被存储 Setting.py

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

models.py

from django.core.files.storage import default_storage
...

class UploadFile(models.Model):
      file = models.FileField(upload_to='docs/')

Forms.py:

class UploadForm(forms.ModelForm):
    documento = forms.FileField(label='Seleccione un archivo',
                                help_text='Max Size 2mb'
                               )
    class Meta:
       model = UploadFile

views.py:

def UploadView(request):
    if request.method == 'POST':
       form = UploadForm(request.POST,request.FILES)
       if form.is_valid():
          form.save()
          return HttpResponseRedirect('/index/')
    else:
       form = DocuForm()
    return render_to_response("yourtemplate.html",
                              {'form':form},
                              context_instance=RequestContext(request))

我在表格中显示文档列表,可以在文件名中单击并下载文件。 如果你想启用文件下载,就用这种方式改变你的urls.py:

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'kp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^upload/$', 'kms.views.UploadView', name='upload'),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)