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

JSF Ajax Link executes a partial ajax render prior to triggering the link action

On my JSF page, I have the following code snippet: <h:commandLink action="#{manager.removeEntity(row.id)}" value="Remove"> <f:ajax event="action" render=":form:table" /> </h:commandLink> Even though the rendering works perfectly, it ...

Unable to retrieve PHP object using AJAX

I am having trouble fetching the PHP file from Ajax. In the PHP file, an object is created and then converted into JSON using the json_encode() function. However, when I try to request that PHP file from Ajax, nothing is displayed as output ('Smith&ap ...

Switching back and forth between classes prevents the animation from playing continuously, causing it to jump straight to the end

Currently, I am in the process of animating a hamburger menu with a unique twist. The idea is to have the top and bottom lines smoothly translate to the middle and then elegantly rotate into an X shape when clicked. My approach involves toggling between tw ...

Table gets duplicated data with JQuery JSON updates

After thorough searching, I couldn't find any relevant information on stack overflow that matches the issue I am encountering. The problem arises with a JQuery ajax request that retrieves JSON data from my server. The structure of the data is as foll ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

JavaScript and AJAX: Dynamically Create URLs

I don't have any experience with web development, so could you please explain in detail? If my questions are unclear, feel free to ask for more information. Imagine I have a webpage with the following URL: www.mycompany.com/category1 This page has ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Returning multiple values in JSON response from AJAX call using ViewBag

Greetings! I have successfully created two dropdown lists. The options in the second dropdown list depend on the selection made in the first dropdown list. Here's an example: Once a value is selected from the 'Call Nature' dropdown list, th ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

showing four forms, unfortunately the last one is malfunctioning

Thank you for taking the time to read this. I've been working on a template that displays 4 forms, each with its own submit button triggering a POST request to the appropriate form. The first 3 forms are functioning correctly, but the last one (Estoq ...

Having trouble with ajax form submission? It was working at first, but suddenly stopped?

Below is the HTML form code found in signup.php: <form id="signup" action="" method="POST" autocomplete="off" autocomplete="false"> <div class="signup_row action"> <input type="text" placeholder="What's your Name?" name="name ...

Passing data between child components using Vuejs 3.2 for seamless communication within the application

In my chess application, I have a total of 3 components: 1 parent component and 2 child components. The first child component, called Board, is responsible for updating the move and FEN (chess notation). const emit = defineEmits(['fen', 'm ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

Building a dynamic dropdown menu for interconnected categories and tags using Ajax in Wordpress

I am currently working on implementing a dynamic filtering system with two dependent dropdown lists for WordPress. The feature I am focusing on is related to recipes, so my specific example should provide more clarity than a general inquiry. Our recipes a ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

"Adjusting the height of a div element while considering the

I have 2 elements with different heights and I want to make them equal: var highestEl = $('#secondElement').height(); $('.element').first().height(highestEl); I understand that the second element is always taller than the first one. W ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...