时间:2021-07-01 10:21:17 帮助过:16人阅读
<!doctype html> <html> <head> <meta name="baidu-site-verification" content="U4mw2VL8NF"/> <meta charset="utf-8"> <title>上传图片</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> <style> @media (min-width: 990px) { .container { width: 960px; } } </style> </head> <body> @include('header') <img id="pic" style="width:100px;height:100px;border-radius:50%;" src="/upload/thumbs/086fa7a88f4f4ab9fce23827a9fc6f22.jpg"> <input id="upload" name="file" accept="image/*" type="file" style="display: none"/> <!-- <ul> <li style="width:23%;float:left;margin:10px;height:200px;background:#eee;"> <img style="height:200px;width:100%;" src="/upload/thumbs/efb3fb08b062a55e28a0e15ad2228514.jpg" alt=""></li> </ul> --> </body> </html> <script> $(function () { $("#pic").click(function () { $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传 $("#upload").on("change", function () { var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径 if (objUrl) { $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片 upimg(); } }); }); }); //建立一個可存取到該file的url function getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { // basic url = window.createObjectURL(file); } else if (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; } //上传头像到服务器 function upimg() { var pic = $('#upload')[0].files[0]; //console.log(pic) var file = new FormData(); file.append('image', pic); $.ajax({ url: "/uploadImg", type: "post", data: file, cache: false, contentType: false, processData: false, success: function (data) { console.log(data); var res = data; //$("#resimg").append("<img src='/" + res + "'>") } }); } // 需要注意几点: // fd.append('name', file); // 这一句中的name是后台需要接受的file的name </script>
相关推荐:
php实现以post方式上传图片文件的方法实例
thinkphp5上传图片及生成缩略图方法
PHP安全地上传图片
以上就是JS上传图片实现代码的详细内容,更多请关注Gxl网其它相关文章!