JQuery отправляет файл в Django

У меня следующая проблема. Когда я отправляю запрос POST с формой:

<form id="uploadForm" action="/theme/zip/type/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="fileInput" class="input-file" name="upload" type="file">
    <input type="submit" value="Upload" />
</form>

Затем на сервере у меня есть код:

print request.FILES

Печать сервера:

<MultiValueDict: {u'upload': [<InMemoryUploadedFile: ID_12241.zip (application/zip)>]}>

Когда я делаю это действие шаг за шагом в коде jQuery:

var content = zip.generate();
var options = {
    url: '/theme/zip/type/',
    data: {
       file: content
    }
};
$('#uploadForm').ajaxSubmit(options);

У меня есть этот файл в параметре «файл» в «request.POST», но «request.FILES» пуст (). Что я делаю неправильно?


person Detonavomek    schedule 22.02.2014    source источник
comment
Вы не можете отправлять файлы с помощью Ajax.   -  person Daniel Roseman    schedule 22.02.2014


Ответы (2)


Взгляните на плагин форм JQUery, он может загружать файлы с помощью ajax.

Согласно документации на их сайте

Browsers that support the XMLHttpRequest Level 2 will be able to upload files seamlessly and even get progress updates as the upload proceeds. For older browsers, a fallback technology is used which involves iframes since it is not possible to upload files using the level 1 implmenentation of the XMLHttpRequest object.

Я использую это в своем проекте, вам не нужно определять iframe для старых браузеров. Этот плагин автоматически сделает это за вас. Ниже приведен пример кода для реализации загрузки файла ajax:

HTML-файл будет выглядеть так (скачайте и дайте ссылку на jquery.form.js в html-файле): -

<form id="uploadForm" method="post" action="/theme/zip/type/"> {% csrf_token %}
    <input type="file" id="fileInput" name="upload"/>
    <button type="submit">Upload</button>
</form>

<script src="jquery-ui.min.js"></script>
<script src="jquery.form.js"></script>

В файле js добавьте следующий код: -

var options = {
    beforeSubmit:showRequest,  // pre-submit callback
    success:showResponse,  // post-submit callback
    resetForm: false        // reset the form after successful submit
};

//uploadForm is the name of your form
$('#uploadForm').submit(function() {
    // inside event callbacks 'this' is the DOM element so we first
    // wrap it in a jQuery object and then invoke ajaxSubmit

    $(this).ajaxSubmit(options);

    // !!! Important !!!
    // always return false to prevent standard browser submit and 
    // page navigation return false;
});

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it 
    // to a string to display it but the form plugin does 
    // this for you automatically when it submits the data 
    var queryString = $.param(formData); 

    // jqForm is a jQuery object encapsulating the form element. 
    // To access the DOM element for the form do this: 
    // var formElement = jqForm[0]; 

    alert('About to submit: \n\n' + queryString); 

    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the 
    // form submit to continue 
    return true; 
} 

// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 

    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 

    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 

    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\noutput div should have been updated with the responseText.'); 
} 

Как только вы нажмете кнопку отправки, будет вызвана функция .submit(). Эта функция возвращает false, что важно для предотвращения обратной передачи браузера. В этой функции определены 2 функции обратного вызова.

  1. showRequest будет вызываться, когда форма будет отправлена, здесь вы можете увидеть все данные поста.
  2. showResponse будет вызываться, когда сервер возвращает ответ.

На сервере вы получите данные в request.FILES. Вернуть ответ JSON с сервера, к которому можно получить доступ в функции showResponse.

person anuragal    schedule 22.02.2014

Ajax в традиционном понимании — это XMLHttpRequest, который не позволяет вам кодировать и отправлять локальные файлы на сервер.

Распространенные способы загрузки с помощью средств «ajax» — либо использовать Flash swf для обработки загрузки на той же странице, либо использовать форму, целью которой является невидимый iframe 1x1.

пытаться

http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

или попробуйте http://www.uploadify.com/

person wholock    schedule 22.02.2014