首页 » PHP » 正文

使用Swfupload实现无刷新上传

发表于: PHP,JS,Golang,Shopify学习交流博客 – 咪啪咪啪的小木屋 · 2015-7-24 ·  4,396 views  ·  0 replies 

77

Swfupload是一款历史时间比较长的Flash上传控件了,最新的2.5版本更新也是在2012年,按常理来讲,大可不必使用这款控件了,毕竟3年不更新了
如果换成别的项目,建议还是使用百度的Web Uploader,可惜IE7以下不支持,因此有时候还是得用一些老插件来代替一下
晚上关于swfupload的教程很多,但是单看说明文档和Demo还是不明白什么意思,下面贴出在使用过程中遇到的问题
目前网上能下载到的swfupload,大多分为两个版本,2.2.0和2.5.0
建议还是使用2.5.0, 2.2.0在IE6下会出现上传按钮出不来的错误,及时安装了Adobe Flash Player也无济于事
解压下载到的swfupload2.5.0,会看到demos和samples两个目录和一个txt文件,demos目录下是样例,samples下则是上传过程中与服务器进行交互的代码
下面对其代码进行解释(针对PHP,其他的语言看不懂)
从demos目录下,找到multiinstancedemo目录,因为这个没有过多的html干扰,因此使用这个进行解释
[sourcecode language=”html”] <title>SWFUpload Demos – Multi-Instance Demo</title>
<link href="../css/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../swfupload/swfupload.js"></script>
<script type="text/javascript" src="../swfupload/swfupload.queue.js"></script>
<script type="text/javascript" src="js/fileprogress.js"></script>
<script type="text/javascript" src="js/handlers.js"></script>
<script type="text/javascript">
var upload1;
window.onload = function() {
upload1 = new SWFUpload({
// Backend Settings
upload_url: "upload.php", //上传时,与服务器端进行交互的代码,如果出现404或者502.记不大清了,试着把这里的路径调成绝对路径
post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"}, //session_id在这里网上有很多解释,加上就可以

// File Upload Settings
file_size_limit : "102400", // 100MB 上传尺寸限制,注意php.ini本身的限制
file_types : "*.*", //文件类型,*.*表示允许所有文件,第二个*代表扩展名,可以根据需要修改
file_types_description : "All Files",
file_upload_limit : 10, //上传数量限制
file_queue_limit : 0,

// Event Handler Settings (all my handlers are in the Handler.js file)
swfupload_preload_handler : preLoad,
swfupload_load_failed_handler : loadFailed,
file_dialog_start_handler : fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,

// Button Settings
button_image_url : "XPButtonUploadText_61x22.png", //上传按钮图片,这个图片的高度为button_height的4倍,注意一下
button_placeholder_id : "spanButtonPlaceholder1",
button_width: 61,
button_height: 22,

// Flash Settings
flash_url : "../swfupload/swfupload.swf", //必要文件
flash9_url : "../swfupload/swfupload_fp9.swf", //必要文件,2.5.0新加,2.2.0是没有这句话的

custom_settings : {
progressTarget : "fsUploadProgress1", //进度条的id
cancelButtonId : "btnCancel1" //取消按钮的id
},

// Debug Settings
debug: false //调试开关,打开会在页面的某个角落出来一个DIV,显示上传时遇到的问题与数据传输的信息,upload_url里面的php代码的输出结果,也会显示在这里
});
}
</script>
</head>
[/sourcecode]

html部分拿demo的实力就可以,看完了demo部分,点击上传按钮,发现并不能使用,因为upload_url:’upload.php’有问题
看看multiinstancedemo里面的upload.php是什么内容
[sourcecode language=”php”] <?php
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
}
session_start();

// The Demos don’t save files

// In this demo we trigger the uploadError event in SWFUpload by returning a status code other than 200 (which is the default returned by PHP)
if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
// Usually we’ll only get an invalid upload if our PHP.INI upload sizes are smaller than the size of the file we allowed
// to be uploaded.
header("HTTP/1.1 500 File Upload Error");
if (isset($_FILES["Filedata"])) {
echo $_FILES["Filedata"]["error"];
}
exit(0);
}

echo "Make sure Flash Player on OS X works";
?>
[/sourcecode]

上面的代码,并没有任何作用,Filedata在index.php也没找到,这时候我们需要去最开始的samples目录下,拿另一个文件过来,才可以使用
目录:/samples/php/upload.php
[sourcecode language=”php”] <?php
// Code for to workaround the Flash Player Session Cookie bug
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
} else if (isset($_GET["PHPSESSID"])) {
session_id($_GET["PHPSESSID"]);
}

session_start();

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get(‘post_max_size’);
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == ‘M’ ? 1048576 : ($unit == ‘K’ ? 1024 : ($unit == ‘G’ ? 1073741824 : 1)));

if ((int)$_SERVER[‘CONTENT_LENGTH’] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
echo "POST exceeded maximum allowed size.";
exit(0);
}

// Settings
$save_path = dirname(__FILENAME__) . "/uploads/"; // The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = "Filedata";
$max_file_size_in_bytes = 2147483647; // 2GB in bytes
$extension_whitelist = array("jpg", "gif", "png"); // Allowed file extensions
$valid_chars_regex = ‘.A-Z0-9_ !@#$%^&()+={}\[\]\’,~`-‘; // Characters allowed in the file name (in a Regular Expression format)

// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = "";
$file_extension = "";
$uploadErrors = array(
0=>"There is no error, the file uploaded successfully",
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);

// Validate the upload
if (!isset($_FILES[$upload_name])) {
HandleError("No upload found in \$_FILES for " . $upload_name);
exit(0);
} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
exit(0);
} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
HandleError("Upload failed is_uploaded_file test.");
exit(0);
} else if (!isset($_FILES[$upload_name][‘name’])) {
HandleError("File has no name.");
exit(0);
}

// Validate the file size (Warning: the largest files supported by this code is 2GB)
$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
if (!$file_size || $file_size > $max_file_size_in_bytes) {
HandleError("File exceeds the maximum allowed size");
exit(0);
}

if ($file_size <= 0) {
HandleError("File size outside allowed lower bound");
exit(0);
}

// Validate file name (for our purposes we’ll just remove invalid characters)
$file_name = preg_replace(‘/[^’.$valid_chars_regex.’]|\.+$/i’, "", basename($_FILES[$upload_name][‘name’]));
if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
HandleError("Invalid file name");
exit(0);
}

// Validate that we won’t over-write an existing file
if (file_exists($save_path . $file_name)) {
HandleError("File with this name already exists");
exit(0);
}

// Validate file extension
$path_info = pathinfo($_FILES[$upload_name][‘name’]);
$file_extension = $path_info["extension"];
$is_valid_extension = false;
foreach ($extension_whitelist as $extension) {
if (strcasecmp($file_extension, $extension) == 0) {
$is_valid_extension = true;
break;
}
}
if (!$is_valid_extension) {
HandleError("Invalid file extension");
exit(0);
}

// Validate file contents (extension and mime-type can’t be trusted)
/*
Validating the file contents is OS and web server configuration dependant. Also, it may not be reliable.
See the comments on this page: http://us2.php.net/fileinfo

Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
which describes how a PHP script can be embedded within a GIF image file.

Therefore, no sample code will be provided here. Research the issue, decide how much security is
needed, and implement a solution that meets the need.
*/

// Process the file
/*
At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
could be done such as creating an entry in a database or generating a thumbnail.

Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
been saved.
*/
//移动临时文件到$save_path.$file_name
if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
HandleError("File could not be saved.");
exit(0);
}

exit(0);

/* Handles the error output. This error message will be sent to the uploadSuccess event handler. The event handler
will have to check for any error messages and react as needed. */
function HandleError($message) {
echo $message;
}
?>
[/sourcecode] 为了清晰起见,我删掉了英文注释,将这个文件的内容放到demo里面去,并在
upload1 = new SWFUpload({
下面加上file_post_name: “Filedata”, 这样就可以了,这句话的对应upload.php里面的$upload_name
以上就是使用方法,附上swfupload2.5.0压缩包以及汉化文档,感谢汉化工作者
http://www.cnblogs.com/youring2/archive/2012/07/13/2590010.html
swfupload下载:

  swfupload 2.5.0 (399.2 KB, 148 次)

:下一篇»

0 thoughts on “使用Swfupload实现无刷新上传”

  1. 还没有任何评论,你来说两句吧

Leave a reply