OiO.lk Blog jQuery Django + jQuery: No Image Provided Error with 400 31 Response When Uploading Image via AJAX
jQuery

Django + jQuery: No Image Provided Error with 400 31 Response When Uploading Image via AJAX


I’m working on a Django project where I’m uploading an image to be processed by a machine learning model. The frontend uses jQuery to send the image via an AJAX request. However, the server keeps returning the error: {"error": "No image provided."} and Accuracy: NaN%. Additionally, I receive the response 400 31 in the browser console.

Frontend (AJAX and HTML Code):

<script>
    $(document).ready(() => {
        $("input[id='image']").on('change', function (event) {
            let input = this;
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#banner').css('width', '350px')
                $('#banner').addClass('img-thumbnail')
                $('#banner').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        })

        $('#process').click(() => {
            $('.buttons').hide()
            $('.loader').show()
            $('#title').html("Processing...")
            let image = $('#image').prop('files')[0]
            var data = image['name'];

            console.log(data)
            $.ajax({
                url: "http://127.0.0.1:8000/api/",
                type: "POST",
                dataType: 'json',
                data: {
                    image: data,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                },
                headers: {
                    'Authorization': 'z*qm$(e9k0wa--t!^ux(xn15vk$)h7c$%3%vflo^@_++bg&uw(', // CSRF token
                    'Content-Type': 'application/json' // JSON
                },
                success: function (xhr) {
                    alert("Error while processing")
                },
                error: function (xhr) {
                    $('#title').html("Result")
                    let result = (xhr.responseText).split("-");
                    let disease = result[0];
                    let accuracy = result[1];
                    $('.loader').hide()
                    $('#disease').html("Result: " + disease)
                    $('#accuracy').html("Accuracy: " + parseInt(accuracy).toFixed(2) + "%")
                    $('#graph').attr('src', '{% static "graph.png" %}')
                    $('.result').show()
                }
            });
        });
    });
</script>

Django Views.py:

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from diab_retina_app import process


@csrf_exempt
def display(request):
    if request.method == 'GET':
        return render(request, 'index.html')


@csrf_exempt
def process_image(request):
    if request.method == 'POST':
        img = request.FILES.get('image')

        if img is None:
            return JsonResponse({'error': 'No image provided.'}, status=400)
        
        print("Image uploaded:", img)  # Log the image details

        try:
            response = process.process_img(img)
            return HttpResponse(response, status=200)
        except ValueError as e:
            return JsonResponse({'error': str(e)}, status=500)

I’ve also verified the following:

  • The file input works on the client-side, and the image is properly displayed before submission.

  • The form data is being constructed, and the image is appended to it.

    But the server still responds with {"error": "No image provided."}.

What could be causing the 400 31 error and the "No image provided" issue? How can I properly send the image file to the Django backend?



You need to sign in to view this answers

Exit mobile version