Ember.js数组去重及PDF文件类型验证脚本优化求助
Hey there! Let's work through your file validation script issue. First, let's spot the problem with your current code: using split("/") directly on the full string splits every slash across the entire text, which gives you messy results (like splitting application/pdf, application/x-pdf into ["application", "pdf, application", "x-pdf", ...]). That's not what you want. Let's fix this step by step.
Step 1: Correctly Extract PDF-Related Suffixes
First, we need to split the MIME type string into individual entries, then pull out the suffix after each slash, and filter out any non-PDF-related entries (like application/acrobat):
const validations = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf"; // Split the full string into individual MIME types const mimeTypes = validations.split(", "); // Extract suffixes and filter only PDF-related ones const pdfSuffixes = mimeTypes .map(mimeType => { const [, suffix] = mimeType.split("/"); // Destructure to grab the part after "/" return suffix; }) .filter(suffix => suffix && suffix.includes("pdf")); // Keep only suffixes linked to PDF
Step 2: Deduplicate the Array (Native JS + Ember.js Options)
Native JavaScript Solution
Your uniqueArray function works, but modern JS has a simpler, more concise way using Set:
const uniquePdfSuffixes = [...new Set(pdfSuffixes)]; // Result: ["pdf", "x-pdf", "vnd.pdf"]
Ember.js Solution
If you're working in an Ember app, Ember's built-in array utilities make deduplication even easier. Wrap your native array with A() to convert it to an Ember array, then use the uniq() method:
import { A } from '@ember/array'; const uniqueEmberSuffixes = A(pdfSuffixes).uniq(); // Result: ["pdf", "x-pdf", "vnd.pdf"]
Full Working Code
Putting it all together, here's the complete script that covers suffix extraction, deduplication, and your file upload validation prompt:
const validations = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf"; // Extract and filter PDF suffixes const pdfSuffixes = validations.split(", ") .map(mimeType => mimeType.split("/")[1]) .filter(suffix => suffix?.includes("pdf")); // Native deduplication const uniqueNative = [...new Set(pdfSuffixes)]; console.log("Native deduped suffixes:", uniqueNative); // Ember.js deduplication import { A } from '@ember/array'; const uniqueEmber = A(pdfSuffixes).uniq(); console.log("Ember deduped suffixes:", uniqueEmber); // Example file upload validation logic const uploadedFileMimeType = "image/jpeg"; // Sample invalid file type const validMimeList = validations.split(", "); if (!validMimeList.includes(uploadedFileMimeType)) { alert("Wrong file type uploaded, only pdf accepted"); }
内容的提问来源于stack exchange,提问作者The Old County

