Django JQuery Ajax File Upload

Viewed 51058

I've been trying to upload a simple text file for hours now but I still can't seem to get it working.

I keep getting invalid forms saying I'm missing the "file_source".

Why is "file_source" not getting posted?

I've also got it to actually send "file_source" but it still says it is missing. What type of element should be given to a Django FileFiled?

Django Form:

class FileUploadForm(forms.Form):
    file_source = forms.FileField()

Django Template (renders form):

<form action="/upload/" method="post" id="file-upload-form" enctype="multipart/form-data"> {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary" id='upload-btn'>Upload</button>
</form>

JQuery/Ajax Upload:

function uploadFile() {
$.ajax({
    data: $(this).serialize(),
    type: $(this).attr('method'),
    url: $(this).attr('action')
});
return false;
}

$(function() {
     $('#file-upload-form').submit(uploadFile);
});

Django View Which recieves POST:

def upload_view(request):
if request.is_ajax():
    form = FileUploadForm(request.POST)
    if form.is_valid():
        print 'valid form'
    else:
        print 'invalid form'
        print form.errors
return HttpResponseRedirect('/ingest/')
3 Answers

Here's how we can send json data in addition to files using Ajax to Django.

Example:

JS using form-data

var formData = new FormData();
formData.append('file1', myFile); 
const data_ = JSON.stringify(data)
formData.append('data', data_);

doPost(url, formData)
.then(result => {
 })

Django using request.FILES & request.POST

data = json.loads(request.POST.get('data'))
 files = request.FILES
 attached_file1 = files.get('file1', None)
 attr1 = data.get('attr1', None)
Related