在Web端开发图片上传功能时,往往需要在上传图片之前对图片进行预览,既可以防止上传错误的图片,又可以大大提升用户体验,但是在IE浏览器上为了提升安全性是不支持上传前预览的,所以需要使用滤镜来实现:(不怎么实用,只是记录下)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<!DOCTYPE html> <html> <head> <script src="jquery/jquery-1.12.4.min.js"></script> <meta charset="utf-8" /> <title>Ajax提交form</title> </head> <body> <img id="preview" width="140" height="100" /> <form id="uploadForm" name="uploadForm" enctype="multipart/form-data" > <input id="file" type="file" onchange="showPic(this)" /> <button id="upload" onclick="doUpload()" type="button">upload</button> </form> <script> //添加图片 $('#addBtn').live('click', function(){ var inputs = $('<input type="file" name="media[]" class="picFile" style="display:none" />'); inputs.appendTo($('#picInput')[0]).end().bind('change', function(){ showPic($(this)[0]); }).trigger('click'); if($('#picInput').children('input').length == 4){ $('#addBtn').attr("disabled", true); } }); //上传图片前显示预览图 function showPic(file){ var img = $('<img class="preview margin-right border" width="110" height="80" />')[0]; if (file.files && file.files[0]) { var reader = new FileReader(); reader.onload = function (evt) { img.src = evt.target.result; } reader.readAsDataURL(file.files[0]); } else { //兼容IE file.select(); var src = document.selection.createRange().text; img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src; } $('#picInput').append(img); } //发布动态 $("#submit").live('click', function () { var form = new FormData($('#form-horizontal')[0]); var status = $.trim($('#status').val()); $.ajax({ url: '/xxxxxx/xxxxx', type: 'post', data: form, cache: false, processData: false, contentType: false, beforeSend: function () { if (status == "") { return false; } }, success: function (data) { console.log(data); } }); }); </script> </body> </html> |
php代码:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php if(!empty($_FILES['file'])){ if (file_exists("pic/" . $_FILES["file"]["name"])){ echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "pic/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } |
转载请注明:PHP笔记 » jQuery实现图片上传之前进行内容预览