简体   繁体   中英

Grabbing a file sent from Django on front-end

I am trying to post a file via http-request (something similar to CURL -F request). So what I want to do is best described by the following code:

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);
});

Basically, the question here is how do I grab the xml file in the client. Thanks in advance!

Some notes

  1. I need the file content to be generated on server-side
  2. I need the file then to be passed to client-side and sent to external server via HTTP request.

Okay so your trying to download a file from django and upload it to another server from your javascript app. I haven't done this before but according to https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data it shouldn't be too difficult.

First, download the binary file:

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();

Next upload the binary file to your other server:

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

    oReq.send(blob);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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