ajaxFileUpload.js
是一个用于处理文件上传的 JavaScript 库。要实现文件类型过滤,你可以在客户端和服务器端都进行文件类型的检查。这里是一个简单的示例,展示了如何在 ajaxFileUpload.js
中实现文件类型过滤:
ajaxFileUpload.js
的 beforeSend
回调函数来检查文件类型。例如,如果你想只允许上传 JPEG 和 PNG 图片,可以这样做:$.ajaxFileUpload({
url: 'your_upload_url',
secureuri: false,
fileElementId: 'file_input_id',
dataType: 'json',
beforeSend: function(data, status) {
var allowedTypes = ['image/jpeg', 'image/png'];
var isValidType = false;
for (var i = 0; i < allowedTypes.length; i++) {
if (data.type === allowedTypes[i]) {
isValidType = true;
break;
}
}
if (!isValidType) {
alert('Invalid file type. Only JPEG and PNG images are allowed.');
return false;
}
},
success: function(data, status) {
// Handle successful upload
},
error: function(data, status, e) {
// Handle error
}
});
Content-Type
或 X-File-Type
字段来检查文件类型。以下是一个使用 Node.js 和 Express 的示例:const express = require('express');
const multer = require('multer');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop());
}
});
const upload = multer({ storage: storage });
app.post('/upload', upload.single('file'), (req, res) => {
const allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(req.file.mimetype)) {
return res.status(400).json({ error: 'Invalid file type. Only JPEG and PNG images are allowed.' });
}
// Handle successful upload
res.json({ message: 'File uploaded successfully' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
这样,你就可以在客户端和服务器端都进行文件类型过滤,确保只有允许的文件类型被上传。