我正在嘗試使用 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); } } });
使用 AJAX 上傳文件在 Django 中不起作用
撒科打諢
2023-10-20 17:37:26