标签:
这里要使用plupload插件
前端js
<script> var uploader = new plupload.Uploader({ //实例化一个plupload上传对象 browse_button: ‘choose‘, url: ‘../ajax_image‘, flash_swf_url: ‘../help/js/Moxie.swf‘, silverlight_xap_url: ‘‘, filters: { mime_types: [ //只允许上传图片文件 { title: "图片文件", extensions: "jpg,gif,png" } ] } }); uploader.init(); //初始化 //绑定文件添加进队列事件 uploader.bind(‘FilesAdded‘, function (uploader, files) { // alert(files[0].size); var msgFlg = 0; for (var i = 0, len = files.length; i < len; i++) { if (files[i].size > 81920) { uploader.files.splice(i, 1); msgFlg = 1; } else { !function (i) { previewImage(files[i], function (imgsrc) { $(‘#file-list‘).html($(‘#file-list‘).html() + ‘<div style="float:left" class="pic_list" id="‘ + files[i].id + ‘">‘ + ‘ (‘ + plupload.formatSize(files[i].size) + ‘)<a href="###" class="pic_delete" data-val=‘ + files[i].id + ‘>删除</a><br/>‘ + ‘<img class="listview" width="90" height="60" src="‘ + imgsrc + ‘" name="‘ + files[i].name + ‘" /></div>‘); }) }(i); } } if (msgFlg == 1) { alert("上传图片小于80K"); return false; } if (uploader.files.length > 0) { //alert(‘请选择图片!‘); //return false; uploader.start(); } }); $(document).on(‘click‘, ‘.pic_list a.pic_delete‘, function () { $(this).parent().remove(); var toremove = ‘‘; var id = $(this).attr("data-val"); for (var i in uploader.files) { if (uploader.files[i].id === id) { toremove = i; $("."+id).remove(); } } uploader.files.splice(toremove, 1); }); uploader.bind("UploadComplete", function (uploader, file) { //console.log(uploader.files[0].id); html = ‘‘; for(i=0;i<uploader.files.length;i++) { html += ‘<input type="hidden" name="xx[]" class="‘+uploader.files[i].id+‘" />‘; } console.log(html); $("#test").html(html); //<input type="hidden" name="xx[]" class=""> //file是文件路径 }); /* function exit() { window.parent.location.href = window.parent.location.href; } */ //plupload中为我们提供了mOxie对象 //有关mOxie的介绍和说明请看:https://github.com/moxiecode/moxie/wiki/API function previewImage(file, callback) {//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数 if (!file || !/image\//.test(file.type)) return; //确保文件是图片 if (file.type == ‘image/gif‘) {//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png var fr = new mOxie.FileReader(); fr.onload = function () { callback(fr.result); fr.destroy(); fr = null; } fr.readAsDataURL(file.getSource()); } else { var preloader = new mOxie.Image(); preloader.onload = function () { //preloader.downsize(550, 400);//先压缩一下要预览的图片,宽300,高300 var imgsrc = preloader.type == ‘image/jpeg‘ ? preloader.getAsDataURL(‘image/jpeg‘, 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据 callback && callback(imgsrc); //callback传入的参数为预览图片的url preloader.destroy(); preloader = null; }; preloader.load(file.getSource()); } } $("#update").bind(‘click‘, function () { //这里看个人需求 你可以直接选择后马上提交 if (uploader.files.length > 0) { //alert(‘请选择图片!‘); //return false; uploader.start(); } }) </script>
服务端代码php
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); $public_path = public_path(); $imagesDir = ‘/upload/images‘; // Settings $targetDir = $public_path . $imagesDir; //$targetDir = ‘uploads‘; $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 = time() . rand(1000, 9999).$_REQUEST["name"]; } elseif (!empty($_FILES)) { $fileName = time() . rand(1000, 9999).$_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); } echo $imagesDir. DIRECTORY_SEPARATOR .$fileName;
插件包自己去下吧
标签:
原文地址:http://www.cnblogs.com/yixi978/p/5765432.html