我正在尝试使用 onchange 事件和 AJAX 上传文件,但它不起作用。我在后端获取文件路径而不是实际文件。我想修改此代码,以便当选择 pdf 文件时,该文件会自动上传并可以在views.py 中使用。a.html:<html> <head> <title> Django image and file upload using ajax </title> </head><body> <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate=""> {%csrf_token%} <input type="file" id="resumes" onchange="funct()" name="resumes"> <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });
1 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
您可以按如下方式发布文件form data:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success : function(data) {
# success
}
});
添加回答
举报
0/150
提交
取消