1 回答
TA贡献2011条经验 获得超2个赞
1、同学Ajax实现文件上传其实很简单的和传统的Form表单提交上传是不用刷新整个页面
2、这个是要看你服务器端用的是什么语言了,PHP、Java还是ASP用法都大同小异
3、前不久刚刚写了个Demo是用PHP实现的你看一下原理,是不是你想要的呢演示地址:www.erdangjiade.com/js/513.html
前端代码为:
<form class="imageform" method="post" enctype="multipart/form-data" action="upload.php"> <div class="up_status" style="display:none"><img src="loader.gif" alt="uploading"/></div> <div class="btn up_btn"> <span>添加图片</span> <input class="photoimg" type="file" name="photoimg"> </div> </form> <div class="preview_img"></div>Jquery代码:
<link rel="stylesheet" type="text/css" href="css/style.css" /> <script type="text/javascript" src="<script type="text/javascript" src="jquery.wallform.js"></script>$("body").on("change", ".photoimg", function() { var obj = $(this); var imageForm = obj.parents(".imageform"); var preview_img = imageForm.next(".preview_img"); var btn = imageForm.find(".up_btn"); imageForm.ajaxForm({ target: preview_img, beforeSubmit: function() { imageForm.next("div.preview_img").html(""); preview_img.hide(); btn.hide(); }, success: function() { preview_img.show(); btn.show(); }, error: function() { btn.show(); preview_img.hide(); } }).submit(); });PHP代码为:
PHP上传 upload.phpif (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if (empty($name)) { echo '请选择要上传的图片'; exit; } $ext = extend($name); if (!in_array($ext, $extArr)) { echo '图片格式错误!'; exit; } if ($size > (1000 * 1024)) { echo '图片大小不能超过1M'; exit; } $image_name = time() . rand(100, 999) . "." . $ext; $tmp = $_FILES['photoimg']['tmp_name']; if (move_uploaded_file($tmp, $path . $image_name)) { echo '<img src="' . $path . $image_name . '" class="preview">'; } else { echo '上传出错了!'; } exit; }效果图:
- 1 回答
- 0 关注
- 534 浏览
添加回答
举报