简体   繁体   English

如何使用没有表单数据的AJAX调用发送文件

[英]How to send a file using AJAX call without form data

我需要从ajax发送一个PDF文件来调用Django服务器,没有表单数据

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添加到$.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;
}

One problem I encountered with Django (rest framework specifically) were the Parser classes. 我遇到的Django(特别是其他框架)遇到的一个问题是Parser类。 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 : 最后不要忘记在settings.py包含django restframework和以下条目:

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
     ]
}

It is all explained here . 这一切都在这里解释。

Hope it helps ! 希望能帮助到你 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM