繁体   English   中英

抓取Django前端发送的文件

[英]Grabbing a file sent from Django on front-end

我试图通过http-request(类似于CURL -F request)发布文件。 因此,我要执行的操作最好由以下代码描述:

def my_view(request):
    string_to_return = '<?xml version="1.0" encoding="UTF-8"?>...'
    file_to_send = ContentFile(string_to_return)
    response     = HttpResponse(file_to_send,'application/xml')
    response['Content-Length']      = file_to_send.size    
    response['Content-Disposition'] = 'attachment; filename="somefile.xml"'
    return response


$.get('/my_view/', function(response){
    var formData = new FormData();

    // file = ??? How do I grab the file ???
    formData.append("thefile", file);
    xhr.send(formData);
});

基本上,这里的问题是如何在客户端中获取xml文件。 提前致谢!

一些注意事项

  1. 我需要在服务器端生成文件内容
  2. 然后,我需要将该文件传递到客户端并通过HTTP请求发送到外部服务器。

好的,因此您尝试从django下载文件并将其从javascript应用程序上传到另一台服务器。 我之前没有做过,但是根据https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data来说,这应该不太困难。

首先,下载二进制文件:

var oReq = new XMLHttpRequest();
oReq.open("GET", "/my_view/", true);
oReq.responseType = "blob";

oReq.onload = function(oEvent) {
  var blob = oReq.response;
  // ...see below for this step
  sendBlob(blob, 'http://www.example.com/other_url');
};

oReq.send();

接下来将二进制文件上传到其他服务器:

function sendBlob(blob, url){
    var oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.onload = function (oEvent) {
      // Uploaded.
    };

    oReq.send(blob);
}

暂无
暂无

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

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