文件下载的原理是通过创建一个链接(a元素),设置其href属性为文件的URL,然后使用download属性指定文件名,最后调用click()方法触发下载。
以下是简单的Web端文件下载的代码示例:
- 返回的url地址进行文件下载
function downloadFile(url, fileName) {
var link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
}
// 调用示例
var fileUrl = 'https://www.example.com/file.pdf';
var fileName = 'document.pdf';
downloadFile(fileUrl, fileName);
- blob流转换为文件并下载,写出web端代码 .createObjectURL() 用于创建 URL 的 File、Blob 或 MediaSource 对象。
function downloadBlob(blob, fileName) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}
- base64转换为文件并下载
// 方法一: 使用Blob对象和URL.createObjectURL
function downloadFileFromBase64(base64String, fileName) {
const byteCharacters = atob(base64String);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
}
// 方法二: 使用data URI
function downloadFileFromBase64DataURI(base64String, fileName) {
const link = document.createElement('a');
link.href = `data:application/octet-stream;base64,${base64String}`;
link.download = fileName;
link.click();
}
// 调用方法一
downloadFileFromBase64(base64String, "file.txt");
// 调用方法二
downloadFileFromBase64DataURI(base64String, "file.txt");
文件上传的原理是通过 HTTP 协议将文件数据传输到服务器端。在 web 端,通常使用 `<input type="file">` 元素来创建文件上传表单。当用户选择文件后,通过 JavaScript 可以监听表单提交事件,获取文件数据,并使用 `FormData` 对象将文件数据包装成一个表单数据对象,然后通过 AJAX 或表单提交的方式将数据发送到服务器端。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileInput" name="file">
<button type="submit">Upload</button>
</form>
<script>
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', fileInput.files[0]);
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
if (response.ok) {
console.log('File uploaded successfully');
} else {
console.error('Failed to upload file');
}
} catch (error) {
console.error('Error uploading file:', error);
}
});
</script>
</body>
</html>