在Web开发中,文件上传是一个常见的功能,它允许用户将文件上传到服务器。JavaScript作为前端开发的重要工具,可以实现这一功能而无需依赖后端语言。本文将详细介绍如何使用JavaScript加载原生文件,并实现文件上传与管理的功能。
一、文件选择与预览
首先,我们需要让用户能够选择文件。这可以通过HTML的<input>元素实现,并设置type属性为file。
<input type="file" id="fileInput" multiple>
接下来,我们可以使用JavaScript来处理文件选择事件,并预览选中的文件。
document.getElementById('fileInput').addEventListener('change', function(event) {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
console.log(`文件名: ${file.name}`);
console.log(`文件大小: ${file.size} bytes`);
console.log(`文件类型: ${file.type}`);
// 预览图片
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
document.body.appendChild(img);
};
reader.readAsDataURL(file);
}
}
});
二、文件上传
文件选择完毕后,我们可以通过AJAX(Asynchronous JavaScript and XML)技术将文件上传到服务器。
function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
fetch('upload.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('文件上传成功:', data);
})
.catch(error => {
console.error('文件上传失败:', error);
});
}
document.getElementById('fileInput').addEventListener('change', function(event) {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
uploadFile(files[i]);
}
});
在上面的代码中,我们使用fetch函数发送POST请求,将文件作为表单数据上传到服务器。服务器端的upload.php需要处理这个请求,并将处理结果返回给客户端。
三、文件管理
上传文件后,我们可能需要管理这些文件,例如查看文件列表、下载文件等。
function getFileList() {
fetch('filelist.php')
.then(response => response.json())
.then(data => {
const fileList = document.getElementById('fileList');
fileList.innerHTML = '';
data.forEach(file => {
const li = document.createElement('li');
li.textContent = file.name;
fileList.appendChild(li);
});
})
.catch(error => {
console.error('获取文件列表失败:', error);
});
}
// 获取文件列表
getFileList();
// 下载文件
function downloadFile(filename) {
fetch(`download.php?filename=${filename}`)
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch(error => {
console.error('下载文件失败:', error);
});
}
在上面的代码中,我们使用fetch函数获取服务器上的文件列表,并将其显示在页面上。同时,我们还提供了一个下载文件的函数,允许用户下载服务器上的文件。
通过以上步骤,我们可以使用JavaScript轻松实现文件上传与管理的功能。当然,实际开发中可能需要根据具体需求进行调整和优化。
