文章詳情頁
Ajax實現(xiàn)上傳圖像功能的示例詳解
瀏覽:143日期:2022-06-12 09:41:49
最終效果展示
xhr發(fā)起請求
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" rel="external nofollow" > <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script></head> <body> <!--1、文件選擇框 --> <input type="file" id="file1"> <!-- 2、上傳文件的按鈕 --> <button id="btnupload">上傳文件</button> <br/> <div><div id="precent"> 0%</div> </div> <!-- 3、img標簽 來顯示上傳成功以后的圖片 --> <img id="img" width="800"> <script> var precent = document.querySelector("#precent")var btnupload = document.querySelector("#btnupload")btnupload.addEventListener("click", function() { var files = document.querySelector("#file1").files if (files.length <= 0) {return alert("請選擇要上傳的文件") } var fd = new FormData() fd.append("avatar", files[0]) var xhr = new XMLHttpRequest() xhr.upload.onprogress = function(e) {console.log(e);if (e.lengthComputable) { var h = Math.ceil((e.loaded / e.total) * 100) precent.style.width = h + "%" precent.innerHTML = h + "%" console.log(h);} } xhr.upload.onload = function() {$("#precent").removeClass().addClass("progress-bar progress-bar-success") } xhr.open("post", "http://www.liulongbin.top:3006/api/upload/avatar") xhr.send(fd) xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText) console.log(data); if (data.status == 200) {console.log("上傳成功");document.querySelector("#img").src = "http://www.liulongbin.top:3006" + data.url } else {console.log("上傳失敗"); }} }}) </script></body> </html>
ajax發(fā)起請求
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="jquery.js"></script> <style>img { width: 50px; height: 50px; display: none;} </style></head> <body> <input type="file" id="file1"> <button id="btnupload">上傳文件</button> </br> <img src="5-121204193R5-50.gif" id="loading"> <script>$(function() { $(document).ajaxStart(function() {$("#loading").show() }) $(document).ajaxStop(function() {$("#loading").hide() }) $("#btnupload").on("click", function() {var files = $("#file1")[0].filesif (files.length <= 0) { alert("請選擇文件")}console.log("ok");var fd = new FormData()fd.append("avatar", files[0])$.ajax({ method: "POST", url: "http://www.liulongbin.top:3006/api/upload/avatar", data: fd, processData: false, contentType: false, success: function(res) {console.log(res); }}) }) }) </script></body> </html>
到此這篇關于Ajax實現(xiàn)上傳圖像功能的示例詳解的文章就介紹到這了,更多相關Ajax上傳圖像內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持!
標簽:
Ajax
排行榜
