我有一些方便的代码可以为我检查文件的文件扩展名,并根据结果附加图像。
如果扩展程序与我列出的任何扩展程序不匹配,我想附加一个通用的'未知'图片。我能做些什么来完成这个?
function get_extension(file_name) {
return file_name.split('.').pop().toLowerCase();
}
function check_file_type(file) {
switch(get_extension(file)) {
//if .jpg/.gif/.png do something
case 'jpg': case 'gif': case 'png':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_image.png')}';
break;
//if .zip/.rar do something else
case 'zip': case 'rar':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_zip.png')}';
break;
//if .pdf do something else
case 'pdf': case 'pptx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_pdf.png')}';
break;
//if .docx do something else
case 'docx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_word.png')}';
break;
//if unknown do something else
case 'WHAT DO I DO HERE' <-- ???
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_other.png')}';
break;
}
}
有什么建议吗?
答案 0 :(得分:4)
使用default:
switch(get_extension(file)) {
//if .jpg/.gif/.png do something
case 'jpg': case 'gif': case 'png':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_image.png')}';
break;
//if .zip/.rar do something else
case 'zip': case 'rar':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_zip.png')}';
break;
//if .pdf do something else
case 'pdf': case 'pptx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_pdf.png')}';
break;
//if .docx do something else
case 'docx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_word.png')}';
break;
//if unknown do something else
default:
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_other.png')}';
break;
}
答案 1 :(得分:3)
如果没有匹配你就不会使用案例,你会使用默认值。它看起来像是:
function get_extension(file_name) {
return file_name.split('.').pop().toLowerCase();
}
function check_file_type(file) {
switch(get_extension(file)) {
//if .jpg/.gif/.png do something
case 'jpg': case 'gif': case 'png':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_image.png')}';
break;
//if .zip/.rar do something else
case 'zip': case 'rar':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_zip.png')}';
break;
//if .pdf do something else
case 'pdf': case 'pptx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_pdf.png')}';
break;
//if .docx do something else
case 'docx':
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_word.png')}';
break;
//if unknown do something else
default:
return '{!URLFOR($Resource.Common, 'images/filetypes/doctype_other.png')}';
break;
}
}