我需要从ajax发送一个PDF文件来调用Django服务器,没有表单数据
答案 0 :(得分:2)
您可以将文件作为原始文件缓冲区发送,如下所示:
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
}
});
});
如果您需要跟踪文件上传的进度,请将xhr
添加到$.ajax()
选项:
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;
}
答案 1 :(得分:1)
我在Django(专门针对其余框架)上遇到的一个问题是Parser类。如果要发送八位字节流,请使用解析器类:
class StreamParser(BaseParser):
media_type = 'octet-stream'
def parse(self, stream, media_type=None, parser_context=None):
return stream.read()
,然后在您的视图类上:
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})
最后不要忘记在settings.py
中包含django restframework和以下条目:
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
here都有详细说明。
希望有帮助!