How can javascript upload a blob?

前端 未结 6 2147
旧时难觅i
旧时难觅i 2020-11-22 11:29

I have a blob data in this structure:

Blob {type: \"audio/wav\", size: 655404, slice: function}
size: 655404
type: \"audio/wav\"
__proto__: Blob
6条回答
  •  情歌与酒
    2020-11-22 11:39

    You actually don't have to use FormData to send a Blob to the server from JavaScript (and a File is also a Blob).

    jQuery example:

    var file = $('#fileInput').get(0).files.item(0); // instance of File
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: file,
      contentType: 'application/my-binary-type', // set accordingly
      processData: false
    });
    

    Vanilla JavaScript example:

    var file = $('#fileInput').get(0).files.item(0); // instance of File
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload.php', true);
    xhr.onload = function(e) { ... };
    xhr.send(file);
    

    Granted, if you are replacing a traditional HTML multipart form with an "AJAX" implementation (that is, your back-end consumes multipart form data), you want to use the FormData object as described in another answer.

    Source: New Tricks in XMLHttpRequest2 | HTML5 Rocks

提交回复
热议问题