Home >Backend Development >PHP Tutorial >JS upload image implementation code
This article mainly shares with you the implementation code of JS uploading images. This article mainly shares it with you in the form of code. I hope it can help you.
<!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>
Related recommendations:
php method example of uploading image files in post mode
thinkphp5 method of uploading images and generating thumbnails
Upload images securely with PHP
The above is the detailed content of JS upload image implementation code. For more information, please follow other related articles on the PHP Chinese website!