There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets uploaded and can be used in views.py.

a.html:

<html>
  <head>
     <title> Custom 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);
           }
       }
   });
   $(document).ready(function(){
     $("#file").change(function(){
       var filename = $("#file").val();
       $.ajax({
           type: "POST",
           url: "",
           enctype: 'multipart/form-data',
           data: {
               file: filename,
           },
           success: function () {
               // alert("Data Uploaded: ");
           }
       });
     })
   })

  </script>
</body>
</html>

Views.py:

def custom_django_image_and_file_upload_ajax(request):
    if request.method == 'POST':
        print("working..............")
        print(request.POST.get('file'))
        print(request.FILES.get('file'))
        print(request.FILES.getlist("file"))
        print("...................................................")
        print(request.POST.get('data'))
        print(request.FILES.get('data'))
        print(request.FILES.getlist("data"))
        return JsonResponse({'error': False, 'message': 'file'})
    return render(request, 'a.html')

Console output upon selecting a file:

System check identified no issues (0 silenced).
December 08, 2020 - 06:55:41
Django version 3.1.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Not Found: /
[08/Dec/2020 06:55:46] "GET / HTTP/1.1" 404 2131
Not Found: /favicon.ico
[08/Dec/2020 06:55:46] "GET /favicon.ico HTTP/1.1" 404 2182
[08/Dec/2020 06:55:51] "GET /URL1/upload/ HTTP/1.1" 200 2318
working..............
C:\fakepath\dummy3.pdf
None
[]
...................................................
None
None
[]
[08/Dec/2020 06:56:09] "POST /URL1/upload/ HTTP/1.1" 200 35

How can I successfully retrieve the file on the backend?

Answer №1

To share the files, you can utilize form data in this way:

let 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) {
       # successful upload
   }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Unable to load image from local source in Vue application

I am currently working on creating a simple dice roll game in VueJs. However, I encountered an issue with using the dice images as it keeps giving me a 404 error. When I attempted to use require(), it stated that the function was not defined. After some t ...

Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for eve ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

Arranging numbers in JavaScript lists

empList = [ { "Account": "AAA - 0029", "Available": "$100" }, { "Account": "BBB- 0146", "Available": "200" }, { "Account": "AAA - 1812", "Available": "300"}, { "Account": "CCC- 2019", "Available": "400"}, { "Account" ...

Password Field Validation in React

<TextField id="outlined-basic" label="Password" variant="outlined" /> Can anyone assist me in implementing password validation using an onchange function? I am seeking help with the ...

Executing a mutation upon mounting using React Apollo 2.1's Mutation component: A Step-by-Step Guide

Currently transitioning from Relay to React Apollo 2.1, and I've encountered a questionable situation. Situation: Certain components should only be displayed if the user is authenticated with an API key. To handle this, there's an Authenticator ...

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

Accessing JSON data through crawling may trigger an "Invalid access" warning

Currently extracting data, I came across this base URL After inspecting chrome's developer tools - Network tab, I found the following URL: international?Adt=1&Chd=0&ECITY1=HKG&ECITY2=ICN&Fa…019.03.13.&TRIP=RT&W ...

Encountering a blank page and error message on Vue JS while attempting to generate a JSON file within the

Recently, I encountered a peculiar problem while working on my Vue project using Vue UI in Visual Studio. Before connecting my API, I wanted to prototype and experiment with fake data. So, I decided to create a JSON file in the assets folder to store my m ...

Sending a post request with Ajax in an ASP.NET Webforms application

When attempting to post data to the server using an AJAX call, I encountered an error. var userDetails = {}; userDetails["Name"] = "Saran"; var DTO = { 'userDetails': userDetails }; $.ajax({ type: "POST", contentTyp ...

I am attempting to save the input value to an array in local storage using VUEX. However, my current method is not producing the desired results

I am facing an issue where I am trying to push an input value and store it in an array in the local storage using VUEX. I have created an array in the state for this purpose. Initially, I push the value and then I stringify it to set the value to the sto ...

Updating VAT amount using AJAX on Cart and Checkout pages in Woocommerce

I have a condition in my code that updates the VAT value to 0 if the condition is true. The code works well, but it requires reloading the page to reflect the updated VAT value. Is there a way to update the VAT value without needing to reload the page? Her ...

smoothly hide the dropdown menu when a link is clicked with a transition effect

I am struggling with two bugs in my dropdown menu that I can't seem to fix. The navigation links on my homepage take users to different sections of the page instantly when clicked. However, the issue arises when the dropdown menu does not close after ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

Error: The cordovaLocalNotification plugin is attempting to read a property 'plugins' that is undefined, resulting in a TypeError

I am currently working on a hybrid application using the Ionic platform. I am trying to integrate Cordova local notification features, but I keep getting an error message saying "cannot read property 'plugins' of undefined." Below is my code. Can ...

Performing subtraction operation on a selected floating-point value from a database using PHP

I am facing an issue with my code where I need to subtract a float value selected from the database and update the subtracted values in the database table. Below is my code snippet: $AmountGiven = $_POST['AmountGiven']; $conn = mysqli_connect("l ...

Learn how to effortlessly download a file from Amazon S3 using Angular and ng-click technology

When attempting to download a file from my Amazon S3 bucket using Angular's ng-click, I am receiving a blank file instead of the expected content. HTML <div class="details-field"> RC Book <font class="digit" >({{rcCount}})</font> ...

Steps to designate a character depending on the frequency of its duplication within an array

I have a series of values in an array that I need to go through and assign incremental numerical values, starting from 1. If the same value appears more than once in the array, I want to append the original assigned number with the letter A, and then B, ac ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...