HTML5 File API readAsBinaryString reads files as much larger, different than files on disk

前端 未结 1 1280
臣服心动
臣服心动 2020-12-04 23:06

Full code at https://gist.github.com/992562.

I am using HTML File API and drag/drop to upload files via XHR post to a PHP script. Procedurally, everything seems to

相关标签:
1条回答
  • 2020-12-04 23:46

    This is probably because you're reading the file as a binary string and constructing the multipart/form-data request manually. For one, you don't need to use FileReader. Since you just want to send the content, try using xhr.send(File) or xhr.send(FormData). The latter constructs and sends a multipart/form-data for you:

    function uploadFiles(url, files) {
      var formData = new FormData();
    
      for (var i = 0, file; file = files[i]; ++i) {
        formData.append(file.name, file);
      }
    
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      xhr.onload = function(e) { ... };
    
      xhr.send(formData);  // multipart/form-data
    }
    
    document.querySelector('input[type="file"]').onchange = function(e) {
      uploadFiles('/server', this.files);
    };
    
    0 讨论(0)
提交回复
热议问题