前端实现上传和下载功能
实现上传功能
在前端页面上创建一个表单,可以使用标签。
监听文件选择事件,获取用户选择的文件对象。
构造FormData对象,并将文件对象添加到FormData中。
使用Fetch或XMLHttpRequest发送请求到后端接口,并将FormData对象作为请求参数传递给后端。
示例代码如下(以Fetch为例):
const fileInput = document.querySelector('input[type=file]');
fileInput.addEventListener('change', async () => {
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);
});
实现下载功能
在前端页面上创建一个按钮,绑定下载事件。
发送请求到后端接口,请求需要下载的文件。
服务器返回二进制流数据,前端进行下载操作。
示例代码如下(以Fetch为例):
const downloadButton = document.querySelector('#download');
downloadButton.addEventListener('click', async () => {
const response = await fetch('/download');
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'file.txt';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});