How can javascript upload a blob?

前端 未结 6 2263
旧时难觅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:43

    2019 Update

    This updates the answers with the latest Fetch API and doesn't need jQuery.

    Disclaimer: doesn't work on IE, Opera Mini and older browsers. See caniuse.

    Basic Fetch

    It could be as simple as:

      fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                    .then(response => console.log(response.text()))
    

    Fetch with Error Handling

    After adding error handling, it could look like:

    fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => {
                    if (response.ok) return response;
                    else throw Error(`Server returned ${response.status}: ${response.statusText}`)
                })
                .then(response => console.log(response.text()))
                .catch(err => {
                    alert(err);
                });
    

    PHP Code

    This is the server-side code in upload.php.

    
    

提交回复
热议问题