Bogdan Dudnik
Bogdan Dudnik

Reputation: 413

html convert text data to file and upload it

Is it possible with javascript to convert text from text-input and upload it as a file to server? I need to add to page something like text editor to open text file, then change it and upload to server as file but not as value of parameter in post request.

So is it possible to do? Thanks.

Upvotes: 0

Views: 211

Answers (1)

Kevin Hakanson
Kevin Hakanson

Reputation: 42200

If the browser supports XMLHttpRequest 2 (see http://caniuse.com/xhr2), you have an option.

The Uploading a file or blob: xhr.send(Blob) section of the HTML5 Rocks Tutorial (New Tricks in XMLHttpRequest2) has some sample code to get you started:

function upload(blobOrFile) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  // Listen to the upload progress.
  var progressBar = document.querySelector('progress');
  xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      progressBar.value = (e.loaded / e.total) * 100;
      progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
    }
  };

  xhr.send(blobOrFile);
}

upload(new Blob(['hello world'], {type: 'text/plain'}));

Upvotes: 1

Related Questions