HTML将文本数据转换为文件并上传

html convert text data to file and upload it

本文关键字:文件 转换 文本 数据 HTML      更新时间:2023-09-26

是否可以使用javascript将文本从文本输入转换为文本并将其作为文件上传到服务器?我需要添加到页面的东西,如文本编辑器打开文本文件,然后改变它,并上传到服务器作为文件,但不是在post请求参数的值。

那么这是可能的吗?谢谢。

如果浏览器支持XMLHttpRequest 2(参见http://caniuse.com/xhr2),您可以选择。

HTML5 Rocks教程(XMLHttpRequest2中的新技巧)的上传文件或blob: xhr.send(blob)部分有一些示例代码可以让您开始:

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