在JQUery Form Plugin看一看,它能够使用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文件看起来像(下载和在HTML文件链接jquery.form.js): -
<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个回调函数。当形式是约提交
showRequest
将被调用,在这里你可以看到所有的POST数据。
showResponse
将在服务器返回响应时调用。
在服务器上,您将在request.FILES中获取数据。从服务器返回可在showResponse
函数中访问的JSON响应。
您无法使用Ajax发送文件。 –