<!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8" /> <title>图片跨域上传示例 - Editor.md examples</title> <link rel="stylesheet" href="css/style.css" /> <link rel="stylesheet" href="../dist/css/editormd.css" /> </head> <body> <div id="layout" style="height: 2000px;background: #f6f6f6;"> <header> <h1>图片跨域上传示例</h1> <p>Image cross-domain upload example.</p> </header> <div id="test-editormd"> <textarea style="display:none;">####跨域上传原理 利用iframe来实现,A站POST到B站,B站处理上传后再跳转回到A站的callback页面,callback页面此时在iframe内(即同域下),再通过window.parent就可以操作父页面的任意元素了。 ####跨域上传示例PHP版 当前域名:blog.xxx.com/post.php ```html <form method="post" target="upload-iframe" enctype="multipart/form-data" action="http://static.xxx.com/uploader.php?callback=http://blog.xxx.com/upload-callback.html"> <input type="file" name="file" accept="image/*" /> <input type="submit" id="submit" value="开始上传" /> </form> <iframe name="upload-iframe" style="display:none;" frameborder="0"></iframe> ``` 图片服务器:static.xxx.com/uploader.php ```php <?php $file = 'uploads/' . $_FILES['file']['name']; // 详细过程略 move_uploaded_file($_FILES['file']['tmp_name'], $file); $location = $_GET['callback'].'?success=1&message=xxxxxxx&url=http://static.xxx.com/2015/02/15'.$file.'&temp='.date('ymdhis'); header('location:' . $location); exit; ?> ``` 当前域名:blog.xxx.com/upload-callback.html ```html <script type="text/javascript"> var query = {}; var urlParams = window.location.search.split('?')[1]; urlParams = urlParams.split("&"); for (var i = 0; i< urlParams.length; i++) { var param = urlParams[i].split("="); query[param[0]] = param[1]; } var imageDialog = window.parent.document.getElementById(query['dialog_id']); //console.log(imageDialog, window.parent.document, window.parent, query); </script> ```</textarea> </div> </div> <script src="js/jquery.min.js"></script> <script src="../src/js/editormd.js"></script> <script type="text/javascript"> $(function() { var testEditor = editormd("test-editormd", { width : "90%", height : 640, markdown : "", path : '../lib/', imageUpload : true, imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"], imageUploadURL : "http://www.ipandao.com/editor.md/examples/php/cross-domain-upload.php", crossDomainUpload : true, uploadCallbackURL : "http://localhost/editor.md/examples/php/upload_callback.html" /* 跨域时,上传的图片服务器后台只需要返回一个跳转URL并跳转到原页面同域下的callback页面,结构如下: { success : 0 | 1, // 0表示上传失败,1表示上传成功 message : "提示的信息,上传成功或上传失败及错误信息等。", dialog_id : $_GET['dialog_id'], url : "远程图片地址" // 上传成功时才返回 } */ }); }); </script> </body> </html>