send a very long string buffer as a file to the server using JavaScript

Hi,

I've a client in JavaScript and a server in Django,
I'm trying to send a very long html text buffer (more than 20,000 characters) to the server.
I think that the best way is to convert is to a file in the client and send it as a file to the server,
but i didn't find a way to do it.

first I tried using post:
var string = escape(html_code);
var params = "value=" + string + '';
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);

Open in new window

but it worked for me only for up to ~10,000 bytes:

than I saw that there is a way to send it using blob:
var blob = new Blob([string], {type: 'text/html'});
...
xhr.send(blob);

Open in new window

But I didn't find a way to get it to work / get it on the server..

also tried:
var xmlDoc = parser.parseFromString(string, "text/xml");

Open in new window


any idea?
thanks!
omer dAsked:
Who is Participating?
 
skijCommented:
Instead of sending it all as one huge post, you may wish to divide it into a number of smaller pieces and then send them sequentially.  You will then need to piece them back together server-side.

var section = 0;
var sectionLength = 900;

window.onload = function(){
var string = escape(document.body.innerHTML);
sendString (string, section, sectionLength);
}

function sendString (string,  section, sectionLength) {
 var params = "value=" + string.substr((section*sectionLength),sectionLength) + '';
 var xhr = new XMLHttpRequest();
 xhr.open("POST", url, true);
 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xhr.setRequestHeader("Content-length", params.length);
 xhr.setRequestHeader("Connection", "close");
 xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            section++;
            if(section*sectionLength <= string.length) {
              sendString (string, section, sectionLength);
            }
            else alert('Done');
        }
    }; 
 xhr.send(params);
}

Open in new window

0
 
omer dAuthor Commented:
thanks, it's a very nice workaround,

but I'll have to handle it in the server side - to save all the chunks in some temp global variable and to save it to disk only when the last request arrive.

but with files it's already being take care, as I can upload also 2 MB file in one request...

I'm looking for a way to upload a big buffer, preferred in one request,
and not getting into managing the chunks uploading in the server side..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.