JavaScript中的Form表单上传文件是通过HTML的<form>
元素和<input type="file">
元素实现的。用户可以通过这个输入框选择本地文件,并通过表单提交到服务器。
以下是一个简单的单文件上传示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
</body>
</html>
在后端(Node.js + Express)处理文件上传:
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.send('File uploaded successfully.');
});
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
原因:
解决方法:
原因:
解决方法:
document.querySelector('form').addEventListener('submit', function(event) {
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
if (file && (file.size > 5 * 1024 * 1024 || !file.type.startsWith('image/'))) {
event.preventDefault();
alert('File must be an image and less than 5MB.');
}
});
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Invalid file type.'));
}
}
});
通过这些措施,可以有效解决常见的文件上传问题,并确保上传过程的安全性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云