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');
});
這樣,你就可以在客戶端和服務器端都進行文件類型過濾,確保只有允許的文件類型被上傳。