0

I'm trying to upload the image file to the Media url specified in my setting.py and store the path of an image in the database table. However, I could not achieve this when using Ajax for uploading the image file..

template.html

<div class="profpic" style="background:url(../../../static/app/img/test.png);background-size:cover">
            <input type="file" id="picpath" name="picpath" class="uploadpic" value=""/>
        </div>

Ajax :

function saveprof() {
            $.ajax({
                type: "POST",
                url: "saveprof",
                enctype: 'multipart/form-data',
                async: true,
                data: {
                    'picpath_Aj': $('#picpath').val(),
                    'profemail_Aj': $('#profemail').val(),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                }
            });
        }

Views.py

def saveprof(request):
if request.method == "POST":
    picpathV = request.POST['picpath_Aj']
else:
    profemailV = ''
    response_data = 'Nothing to update!'
    return HttpResponse(response_data, content_type="text/plain")
response_data = 'Empty'
try:
    res=td_table.objects.filter(id=request.session.get('proid')).update(picpath=picpathV)
except:
    response_data = 'Something went wrong!'
return HttpResponse(response_data, content_type="text/plain")

Above code is working fine, but I could save only the file path like ('C:\fakepath\file.jpg').. and file is not getting saved to the media path provided in the Settings.py.

I could upload the file when I use request.FILES in the view, when used Django form.. but in my case, I need to get this done using Ajax function only. What could be the wrong in the view code ?

Here is my models.py

class td_Student(models.Model):
firstname = models.CharField(max_length=300,blank=True)
picpath=models.FileField(upload_to=unique_filename)

def unique_filename(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s_%s.%s" %(uuid.uuid4(),time.strftime("%Y%m%d_%H%M%S"), ext)
    return os.path.join('documents/documents/'+time.strftime("%Y%m%d"), filename)

As per above logic, file name should be like 'documents/documents/20150716/a1f81a80-ce6f-446b-9b49-716b5c67a46e_20150716_222614.jpg' - This value should be stored in my database table.

settings.py

MEDIA_ROOT = 'C:/DJ/'
MEDIA_URL = '/DJ/'

1 Answer 1

2

The problem is not with Django, but with your AJAX post, you are just passing the name, hence Django receives and saves the name.

Solution: Once the user selects a file, change event will be emitteed, on this change evet you will have to grab the file instance using event.target.files store it in a local variable and pass it to picpath_Aj'.

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

Detailed guide is here http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

And alternative Django solution with JS and backend code is https://github.com/skoczen/django-ajax-uploader

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks kumar. I will try this method. I thought, there could be some possibility within Django itself which I'm missing out.. but this is quite useful as well.
Sathish, Django being server side, cannot access client files with path, so the file stream must be uploaded from the client either via JS or via HTML forms.
I agree. But I need to write the server side code in Django to upload the files as per the given example in abandon.ie.. Have you come across any working example for uploading the file using Ajax and Python django without html form ?
Hi Kumar, I have a question.. Can I use form for File upload and send that form data via my Ajax method ?? is this possible ?, if so, DJango can store the file uploaded in the server.
Yes that's what the JS that I gave does, it reads from the file inout field and grabs the file instance. So you can use that instance when you are posting via Ajax, but read the full guide, there are some caveats with Content-Type etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.