我正在创建一个Facebook应用程序,允许用户通过html表单上传照片。我想知道在提交表单之前可以实现一个过滤器来检查文件ext。
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
Choose a file to upload: <br/>
<input name="uploadedfile" type="file" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'" accept="image/gif,image/png,image/jpeg"/> (limit: 2MB)<br />
<input type="submit" value="Upload File" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'"
onclick='checkExt()'/>
</form>
我尝试了不同的方式,javascript或php。
function checkExt() {
var filePath = document.getElementByName("uploadedfile");
if(filePath.indexOf('.') == -1)
return false;
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
validExtensions[0] = 'jpg';
validExtensions[1] = 'jpeg';
validExtensions[2] = 'bmp';
validExtensions[3] = 'png';
validExtensions[4] = 'gif';
for(var i = 0; i < validExtensions.length; i++) {
if(ext == validExtensions[i])
return true;
}
top.location.href = 'http://www.google.com';
return false;
}
对于php,有没有办法在表单提交之前获取文件信息?
$file = document.getElementByName("uploadedFile"); //wondering if this works.
$result_array = getimagesize($file);
if ($result_array !== false) {
$mime_type = $result_array['mime'];
switch($mime_type) {
case "image/jpeg":
echo "file is jpeg type";
break;
case "image/gif":
echo "file is gif type";
break;
default:
echo "file is an image, but not of gif or jpeg type";
}
} else {
echo "file is not a valid image file";
}
请指教。我还是facebook应用程序的新手。
答案 0 :(得分:1)
如果他们尝试上传错误的分机,为什么要重定向?
我会删除top.location.href = 'http://www.google.com';
脚本中有几个错误。
var filePath = document.getElementByName("uploadedfile");
需要
var filePath = document.getElementsByName("uploadedfile")[0].value;
或添加ID并执行
var filePath = document.getElementById("uploadedfile").value;
或使用我最喜欢的方法并将表单对象传递给函数:
<form onsubmit="return checkExt(this)" ...>
function checkExt(theForm) {
var filePath = theForm.uploadedfile.value;
最后从提交中删除onclick并将其放在表单的onsubmit中:
<form enctype="multipart/form-data" action="uploader.php" method="POST"
onSubmit="return checkExt(this)">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
Choose a file to upload: <br/>
<input name="uploadedfile" id="uploadedfile" type="file" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'" accept="image/gif,image/png,image/jpeg"/> (limit: 2MB)<br />
<input type="submit" value="Upload File" class="btn"
onmouseover="this.className='btn btnhov'" onmouseout="this.className='btn'"/>
</form>
答案 1 :(得分:0)
只是一些想法: