简体   繁体   中英

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.

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

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