JavaScript 如何上传Blob
在JavaScript中,有多种方法可以上传Blob(一组保存在文件中的数据字节),包括使用XMLHttpRequest、Fetch API、jQuery等。在本教程中,我们将讨论大多数浏览器支持的两种最常见的方法。
注意: 要测试我们的HTTP请求,您可以使用minimal express服务器。您也可以使用任何在线测试工具,如webhook.site。
Fetch API: Fetch API允许Web浏览器通过HTTP请求发送和接收数据。它是XMLHttpRequest的简化版本。fetch()方法返回一个Promise,可以通过then()和catch()进行链式处理以更好地处理错误。除了IE之外,它被所有现代浏览器支持。
语法:
fetch( url, // API endpoint
{
method:"", // HTTP Method (GET, POST, PUT, DELETE)
body: {}, // Data to be sent
}).then(response => {
// handle the response
})
.catch(e => {
// handle the error
});
示例:
JavaScript
<script>
function uploadBlob() {
const blob =
new Blob(
["This is some important text"],
{ type: "text/plain" }
);
// Creating a new blob
// Hostname and port of the local server
fetch('http://localhost:3000', {
// HTTP request type
method: "POST",
// Sending our blob with our request
body: blob
})
.then(response => alert('Blob Uploaded'))
.catch(err => alert(err));
}
document.addEventListener('load', uploadBlob())
</script>
输出:

AJAX: 它是一组可以在不重新加载当前页面的情况下,异步地从服务器发送和检索数据的Web应用程序。在调用ajax函数之前,请导入或加载jQuery。
语法:
$.ajax({
url: "", // API Endpoint
type: "", // HTTP Method (GET, POST, PUT, DELETE)
data: {}, // Data to be sent
// Specifies how the form-data should be encoded
enctype: 'multipart/form-data',
success: function(data) {
// Handle the response
}, error: function(e) {
// Handle the error
}
});
示例:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
</head>
<body>
<script>
function uploadBlob() {
const blob = new Blob(
["This is some important text"],
{ type: "text/plain" }
);
// Creating a new blob
.ajax({
// Hostname and port of the local server
url: "http://localhost:3000/",
// HTTP request type
type: "POST",
// Sending blob with our request
data: blob,
processData: false,
contentType: false,
success: function (data) {
alert('Blob Uploaded')
},
error: function (e) {
alert(e);
}
});
}
(document).on('load', uploadBlob());
</script>
</body>
</html>
输出:

极客教程