Uploadify是基于jquery的一款文件上传插件,功能非常丰富,使用也比较方便,我们来看看怎么使用吧,我用这个插件是费了一番周折啊,主要是服务器配置稍不注意就不能运行。(我的环境是win7+IIS7.5)
首先下载Uploadify,解压放在服务器上,在根目录下创建文件夹tmp(作为存储php上传的临时文件夹,这里好像必须是tmp这个名字,不然上传会失败),创建uploads文件夹作为存储上传资源使用。
修改php.ini中关于上传的配置,主要是下面三个配置项(其中临时文件夹如果用C:\Windows\Temp这里会出问题,f:\asp是网站的根目录)
upload_tmp_dir = "f:\asp\tmp\" upload_max_filesize = 100M post_max_size = 80M为了测试上传大文件,配置的大小限额还是比较大的,默认分别是10M和8M。修改完毕后重启IIS服务器。
下面我们来写一个前台页面测试uploadify的上传功能
<!DOCTYPE html> <html> <head> <title>My Uploadify Implementation</title> <link rel="stylesheet" type="text/css" href="uploadify.css"> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="jquery.uploadify-3.1.js"></script> <script type="text/javascript"> $(function() { $('#file_upload').uploadify({ 'swf' : 'uploadify.swf', 'uploader' : 'uploadify.php' // Your options here }); }); </script> </head> <body> <input type="file" name="file_upload" id="file_upload" /> </body> </html>
下面是后台处理上传文件的脚本(注意:flash插件将表单名file_upload改成了Filedata,所以我们获取$_FILES信息需要用Filedata才行)
<?php /* Uploadify Copyright (c) 2012 Reactive Apps, Ronnie Garcia Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ // Define a destination $targetFolder = '/uploads'; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('jpg','jpeg','gif','png','zip', 'rar','txt','exe','php','ppt','doc'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,iconv("UTF-8","gb2312", $targetFile)); //move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } ?>为了处理中文文件名上传的情况,需要将$targetFile进行编码转换,不然上传中文名的文件会失败。下面是上传的效果。
如果不用这个插件我们需要怎么实现上传文件呢,来看看下面的代码
<html> <head></head> <body> <form enctype="multipart/form-data" action="uploadify.php" method="POST"> <!-- Name of input element determines name in $_FILES array --> Send this file: <input name="Filedata" id="Filedata" type="file" /> <input name="tt" type="submit" value="Send File" /> </form> </body> </html>可以看出我们需要制定form的encrypt属性必须为"multipart/form-data" ,令我费解的是flash插件实现上传的时候服务器端获取到的属性却是“application/octet-stream”,不过不管怎样,能方便地实现文件上传还是很好的,uploadify功能还很丰富,提供很多回调接口使用,比如上传暂停,取消等,多文件上传也能轻松实现。以后做文件上传的时候可以考虑用用这个插件。