简述:
验证图片上传时合法的图片文件
代码:
utilties.js
/**
* 忽略大小写比较
*/
function compareIgnoreCase(para1, para2){
return para1.toUpperCase() == para2.toUpperCase();
}
/**
* 检测是否是图片格式
*/
function checkIsImageType(filePath){
var indexOfLastDot = filePath.lastIndexOf(".");
var fileType = filePath.substring(indexOfLastDot + 1);
if(compareIgnoreCase(fileType, "jpg"))
return true;
if(compareIgnoreCase(fileType, "jpeg"))
return true;
if(compareIgnoreCase(fileType, "png"))
return true;
return false;
}
图片上传时的验证
//图片格式检测
if(!checkIsImageType($('#fileToUpload').val())){
alert("非合法的图片格式");
return;
}
function ajaxFileUpload()
{
if($('#fileToUpload').val() == ""){
alert("未选择文件 无法上传");
return;
}
//图片格式检测
if( !checkIsImageType($('#fileToUpload').val()) ){
alert("非合法的图片格式");
return;
}
// if(compareIgnoreCase())
showLoading("正在上传,请等待...");
$.ajaxFileUpload
(
{
url:'${ctx}/fileUpload?action=uploadPic',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'fileToUpload',//文件上传空间的id属性 <input type="file" id="fileToUpload" name="fileToUpload" />
dataType: 'json',//返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
dismissLoading();
}else
{
$('#uploadImg').attr("src", data.msg);
$('#uploadImg').css("display", 'block');
$('#uploadImgUrl').attr("value",data.msg);
dismissLoading();
}
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
dismissLoading();
}
}
)
}
上传部分的Html
<input id="fileToUpload" type="file" size="0" name="fileToUpload" class="input">
<a href="javascript:ajaxFileUpload()" id="buttonUpload" value="上传" class="btngray02">上传图片</a>
<img id="uploadImg" width="75" height="100" style="display:none;margin-right:5px;float:right;float:top"/>