Ajax 无刷新上传文件插件 uploadify 的使用

时间:2023-03-08 17:16:49

在表单中无法直接使用 Ajax 上传文件,解决的思路可以是使用插件无刷新地上传文件,返回文件上传后的地址,然后把该地址作为 Ajax 的参数传递给服务器端进行数据库处理。可以使用 uploadify 插件来实现该思路。

官方网站:http://www.uploadify.com

文档地址:http://www.uploadify.com/documentation/

插件有 Flash 版 和 HTML5 版,项目中用到的是 Flash 版。

下载 Demo 并解压:

Ajax 无刷新上传文件插件 uploadify 的使用

其中 index.php :包含了 html ,并且调用了核心 js 库的接口;

jquery.uploadify.js :核心 js 库;

uploadify.php :处理上传,并且返回上传是否成功的状态值。

对官方 demo 稍作修改:

index.html 主要代码

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="__PUBLIC__/css/uploadify.css" type="text/css">
<script src="__PUBLIC__/js/Jquery-1.8.3.js.js"></script>
<script src="__PUBLIC__/js/jquery.uploadify.js" type="text/javascript"></script>
<script src="__PUBLIC__/js/upload.js" type="text/javascript"></script>
</head> <body>
<form id="upform">
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
</body>
</html>

upload.js 代码:

$(function(){
$timestamp = $("#timestamp").html();
$token = $("#token").html();
$swfurl = $("#swfurl").html();
$('#file_upload').uploadify({
'formData' : {
'timestamp' : $timestamp,
'token' : $token
},
'swf' : $swfurl,
'uploader' : 'uploadify.php',
'onUploadSuccess' : function(file, data, response) {
var dataObj = eval("(" + data + ")");
if(1 == dataObj.code){
$msg = '文件'+ file.name + '上传成功';
$("#msg").html($msg);
$("#filename").html(dataObj.filename);
}else if(2 == dataObj.code){
$msg = '文件上传失败,请上传小于2M的.dox、.docx、.pdf文件';
layer.msg($msg, 2, 3);
}else if(3 == dataObj.code){
$msg = '文件类型错误';
layer.msg($msg, 2, 3);
}else{
$msg = '上传失败,请上传小于2M的.dox、.docx、.pdf文件';
layer.msg($msg, 2, 3);
}
}
});
})

uploadify.php

<?php
$targetFolder = './Uploads/authorization';
$verifyToken = md5('unique_salt' . $_POST['timestamp']); if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $fileTypes = array('doc','docx','pdf');
$fileParts = pathinfo($_FILES['Filedata']['name']); $filename = $_SESSION['member']['mid'].'-'.date('Ymd-His').'-'. mt_rand(0,1000).'.'.$fileParts['extension'];
$targetFile = rtrim($targetPath,'/') . '/' . $filename; if (in_array($fileParts['extension'],$fileTypes)) {
if(move_uploaded_file($tempFile,$targetFile)){
$arr['code']= 1;
}else{
//上传失败
$arr['code'] = 2;
$arr['file_name'] = '';
}
} else {
//文件类型错误
$arr['code'] = 3;
$arr['file_name'] = '';
}
}else{
$arr['code'] = 4;
$arr['file_name'] = '';
}
$arr['filename'] = $filename;
exit(json_encode($arr));