关于plupload跨域问题
假设我们页面或者应用已在 http://www.test1.com 上了,而我们打算从 http://www.test2.com 请求提取数据。一般情况下,如果我们直接使用 AJAX 来请求将会失败,浏览器也会返回“源不匹配”的错误,"跨域"也就以此由来。
利用 CORS,http://www.test2.com 只需添加一个标头,就可以允许来自 http://www.test1.com 的请求,下图是我在PHP中的 hander() 设置,“*”号表示允许任何域向我们的服务端提交请求:

也可以设置指定的域名,如域名 http://www.test2.com ,那么就允许来自这个域名的请求:

当前我设置的header为“*”,任意一个请求过来之后服务端我们都可以进行处理&响应,那么在调试工具中可以看到其头信息设置,其中见红框中有一项信息是“Access-Control-Allow-Origin:* ”,表示我们已经启用CORS。
- 刚刚说到的兼容性。CORS是W3C中一项较新的方案,所以部分浏览器还没有对其进行支持或者完美支持,详情可移至 http://www.w3.org/TR/cors/
- 安全问题。CORS提供了一种跨域请求方案,但没有为安全访问提供足够的保障机制,如果你需要信息的绝对安全,不要依赖CORS当中的权限制度,应当使用更多其它的措施来保障,比如OAuth2。
自认为的cors使用场景:
- cors在移动终端支持的不错,可以考虑在移动端全面尝试;PC上有不兼容和没有完美支持,所以小心踩坑。当然浏览器兼容就是个伪命题,说不准某个浏览器的某个版本就完美兼容了,说不准就有点小坑,尼玛伤不起!~
- jsonp是get形式,承载的信息量有限,所以信息量较大时CORS是不二选择;
- 配合新的JSAPI(fileapi、xhr2等)一起使用,实现强大的新体验功能。
- CORS浏览器支持情况如下图:

转载自:http://www.cnblogs.com/Darren_code/p/cors.html
今天使用plupload要跨域上传文件,但是发现会报错的,是一个options 304错误。本地上传没有问题,于是考虑这个上传插件可能没有考虑到跨域问题于是参考上面的资料在前面加上这个代码:
header("Access-Control-Allow-Origin:*");//加在这里 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache");
于是这个错误解决了,但是又返回了一个100的错误,触发的代码在upload.php:
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
经过试验,
//$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "file";
$targetDir = 'file';
$targetDir = 'file';
将$targetDir直接命名为传入文件的默认文件夹名即可
自此plupload可以正常使用
示例代码如下:
custom.php:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Plupload - Custom example</title> <!-- production --> <script type="text/javascript" src="http://172.37.65.100/js1/plupload.full.min.js"></script> <!-- debug <script type="text/javascript" src="../js/moxie.js"></script> <script type="text/javascript" src="../js/plupload.dev.js"></script> --> </head> <body style="font: 13px Verdana; background: #eee; color: #333"> <h1>Custom example</h1> <p>Shows you how to use the core plupload API.</p> <div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div> <br /> <div id="container"> <a id="pickfiles" href="javascript:;">请选择文件</a> <a id="uploadfiles" href="javascript:;">上传文件</a> </div> <br /> <pre id="console"></pre> <script type="text/javascript"> // Custom example logic var baseurl = "<?php echo 'http://ip'; ?>"; var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight,html4', browse_button : 'pickfiles', // you can pass an id... container: document.getElementById('container'), // ... or DOM Element itself url : baseurl +'/upload.php', flash_swf_url : 'http://172.37.65.100/js1/Moxie.swf', silverlight_xap_url : 'http://172.37.65.100/js1/Moxie.xap', filters : { max_file_size : '10mb', mime_types: [ {title : "Image files", extensions : "jpg,gif,png"}, {title : "Zip files", extensions : "zip"} ] }, init: { PostInit: function() { document.getElementById('filelist').innerHTML = ''; document.getElementById('uploadfiles').onclick = function() { uploader.start(); return false; }; }, FilesAdded: function(up, files) { log('[FilesAdded]'); plupload.each(files, function(file) { log(' File:', file); document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>'; }); }, UploadProgress: function(up, file) { document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>"; }, UploadComplete: function(up, files) { // Called when all files are either uploaded or failed log('[UploadComplete]'); }, Error: function(up, err) { document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); } } }); function log() { var str = ""; plupload.each(arguments, function(arg) { var row = ""; if (typeof(arg) != "string") { plupload.each(arg, function(value, key) { // Convert items in File objects to human readable form if (arg instanceof plupload.File) { // Convert status to human readable switch (value) { case plupload.QUEUED: value = 'QUEUED'; break; case plupload.UPLOADING: value = 'UPLOADING'; break; case plupload.FAILED: value = 'FAILED'; break; case plupload.DONE: value = 'DONE'; break; } } if (typeof(value) != "function") { row += (row ? ', ' : '') + key + '=' + value; } }); str += row + " "; } else { str += arg + " "; } }); var log = document.getElementById('console'); log.innerHTML += str + "\n"; } uploader.init(); //绑定各种事件,并在事件监听函数中做你想做的事 uploader.bind('FilesAdded',function(uploader,files){ //每个事件监听函数都会传入一些很有用的参数, //我们可以利用这些参数提供的信息来做比如更新UI,提示上传进度等操作 }); uploader.bind('UploadComplete',function(uploader,file){ //每个事件监听函数都会传入一些很有用的参数, //我们可以利用这些参数提供的信息来做比如更新UI,提示上传进度等操作 }); </script> </body> </html>
upload.php:
<?php
/**
* upload.php
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
#!! IMPORTANT:
#!! this file is just an example, it doesn't incorporate any security checks and
#!! is not recommended to be used in production environment as it is. Be sure to
#!! revise it and customize to your needs.
// Make sure file is not cached (as it happens for example on iOS devices)
header("Access-Control-Allow-Origin:*");//加在这里
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
/*
// Support CORS
header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit; // finish preflight CORS requests here
}
*/
// 5 minutes execution time
@set_time_limit(5 * 60);
// Uncomment this one to fake upload time
// usleep(5000);
// Settings
//$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "file";
$targetDir = 'file';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
// Return Success JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

浙公网安备 33010602011771号