2

そのため、外部プラグインなしでファイルをアップロードしようとしていますが、いくつかのエラーが発生しています。

                <form method="" action="" name='upload_form' id='upload_form' >
                    {% csrf_token %}
                   <input type='file' name='file' id='file' />
                   <input type='button' value='Upload' id='upload'/>
                </form>

                <script type='text/javascript'>
                $(document).ready(function() {
                    var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
                    $('#upload').click(function() {
                        $.ajax({
                            csrfmiddlewaretoken: csrf_token,
                            type: 'POST',
                            url : 'upload',
                            enctype: "multipart/form-data",
                            data  : {
                                'file': $('#file').val()
                            },
                            success: function(data) {
                                console.log(data)
                            }
                        })
                    })
                })
                </script>

私のサーバー:

class ImageUploadView(LoginRequiredMixin, JSONResponseMixin, AjaxResponseMixin, CurrentUserIdMixin, View):

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super(ImageUploadView, self).dispatch(*args, **kwargs)

    def post_ajax(self, request, username):
                print request.POST.get('file', None)
                print request.FILES

        # id = request.POST['id']
        # path = 'pictures/'
        # f = request.FILES['picture']
        # destination = open(path, 'wb+')
        # for chunk in f.chunks():
        #   destination.write(chunk)
        # destination.close()
return HttpResponse("image uploaded")

<MultiValueDict: {}>request.FILES に対してを取得します。

アップロードされたファイルを自分のコードで適切に取得するにはどうすればよいですか?

4

2 に答える 2

5

これは、JavaScriptを使用してファイルをアップロードするために使用するものです。これが役立つことを願っています! $('#file') をパラメーターとして渡すだけです。

function upload(field, upload_url) {
    if (field.files.length == 0) {
        return;
    }
    file = field.files[0];
    var formdata = new FormData();
    formdata.append('file_upload', file);
    $.ajax({
        url: upload_url,
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
        success: console.log('success!')
    });
}

[編集]

そして、これは私がサーバー側で行うことです(簡略化):

def save_file(dest_path, f, filename):
    original_name, file_extension = os.path.splitext(f.name)
    filename = filename + '-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + file_extension
    url = '/' + dest_path + '/' + filename
    path = django_settings.MEDIA_ROOT + url
    destination = open(path, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    return path

class FileUploadView(View):
    def post(self, request, *args, **kwargs):
        if request.FILES and request.FILES.get('file_upload'):
            path = save_file(UPLOAD_TO, 
                             request.FILES.get('file_upload'), 
                             FILENAME)
        return self.render_to_response({})
于 2013-05-14T14:28:39.130 に答える