Reputation: 197
I need to send a PDF file from ajax to call to Django server, without form data
Upvotes: 1
Views: 7383
Reputation: 420
One problem I encountered with Django (rest framework specifically) were the Parser classes. If you want to send octet-stream then use a parser class :
class StreamParser(BaseParser):
media_type = 'octet-stream'
def parse(self, stream, media_type=None, parser_context=None):
return stream.read()
and then on your view class:
class ExampleView(APIView):
"""
A view that can accept POST requests with JSON content.
"""
parser_classes = [StreamParser]
def post(self, request, format=None):
return Response({'received data': request.data})
Finally do not forget to include django restframework and the following entry in settings.py
:
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
It is all explained here.
Hope it helps !
Upvotes: 1
Reputation: 1374
You can send your files as raw file buffer as follows:
var input = $('#input');
input.change(function(event) {
var file = this.files[0];
if (!file) return;
return $.ajax({
url: '/django-route', // your route to process the file
type: 'POST', //
data: file,
processData: false,
contentType: 'application/octet-stream', // set Content-Type header
success: function(respnse) {
// do something
},
error: function(xhr, textStatus, errorThrown) {
// do something else
}
});
});
If you need to track the progress of your file upload, add the xhr
to $.ajax()
options:
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var progress = Math.floor(10000 * event.loaded / event.total) / 10000;
console.log(progress); // 0.2536 (25.36%)
}
}, false);
xhr.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var progress = Math.floor(10000 * event.loaded / event.total) / 10000;
console.log(progress);
}
}, false);
return xhr;
}
Upvotes: 6