在前端开发中,文件流请求是一个常见的操作,无论是上传文件还是下载文件,都离不开文件流请求。今天,我们就来聊聊如何轻松掌握前端文件流请求,即使是前端小白也能轻松学会。
什么是文件流请求?
文件流请求,顾名思义,就是指在请求过程中,数据以流的形式传输。在浏览器中,文件流请求通常使用 XMLHttpRequest 或 fetch API 来实现。
使用 XMLHttpRequest 进行文件流请求
1. 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
2. 设置请求类型和 URL
xhr.open('POST', 'http://example.com/upload', true);
3. 设置请求头
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
4. 监听请求事件
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
console.log('上传进度:' + percentComplete + '%');
}
};
xhr.onload = function() {
if (xhr.status === 200) {
console.log('上传成功');
} else {
console.log('上传失败');
}
};
5. 发送请求
var formData = new FormData();
formData.append('file', document.getElementById('file').files[0]);
xhr.send(formData);
使用 fetch API 进行文件流请求
1. 使用 fetch API 发起请求
fetch('http://example.com/upload', {
method: 'POST',
body: new FormData(document.getElementById('form'))
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. 监听请求事件
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/upload', true);
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
console.log('上传进度:' + percentComplete + '%');
}
};
xhr.onload = function() {
if (xhr.status === 200) {
console.log('上传成功');
} else {
console.log('上传失败');
}
};
xhr.send(new FormData(document.getElementById('form')));
下载文件
1. 使用 fetch API 下载文件
fetch('http://example.com/file')
.then(response => response.blob())
.then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'example.txt';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
});
2. 使用 XMLHttpRequest 下载文件
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/file', true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
let url = window.URL.createObjectURL(xhr.response);
let a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'example.txt';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
};
xhr.send();
总结
通过以上介绍,相信大家对前端文件流请求有了更深入的了解。在实际开发中,我们可以根据需求选择合适的请求方法,并合理利用事件监听,实现文件的上传和下载。希望这篇文章能帮助到大家,祝大家前端开发愉快!
