網(wǎng)站式登錄頁面模板下載營銷軟文范例大全
無樣式上傳圖片
創(chuàng)建一個 FormData
對象:這個對象可以用于存儲數(shù)據(jù)。
將文件添加到 FormData
對象:通過 append()
方法,將用戶選擇的文件添加到 formData
對象中。
使用 fetch
發(fā)送請求:使用 fetch
API 或者其他方法將 FormData
對象發(fā)送到服務(wù)器。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>圖片上傳</title></head><body><!-- 文件上傳 --><input type="file" id="fileInput" onchange="uploadImage()" /><script>// 上傳圖片的函數(shù)function uploadImage() {// 獲取文件輸入框元素const fileInput = document.getElementById("fileInput");// 創(chuàng)建formData對象,用于存儲要上傳的文件數(shù)據(jù)const formData = new FormData();formData.append("file", fileInput.files[0]); // 將選中的文件添加到formData對象中// 請求接口fetch("http://yikatong.kuxia.top/pc/common/upload", {method: "POST",body: formData, // 請求體是formData對象,其中包含文件數(shù)據(jù)}).then((response) => response.json()) // 服務(wù)器響應(yīng)成功后,解析JSON格式的響應(yīng)數(shù)據(jù).then((data) => {console.log("上傳成功:", data);}).catch((error) => {console.error("上傳失敗:", error);});}</script></body>
</html>
有樣式的上傳圖片
?就是把圖片回顯的地方蓋著輸入框
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>圖片上傳</title></head><style>* {padding: 0;margin: 0;}.box {display: flex;}/* 添加虛線邊框 */#image {width: 100px;height: 100px;border-radius: 5px;margin-left: -100px;}</style><body><div class="box"><!-- 文件上傳 --><inputtype="file"id="fileInput"onchange="uploadImage()"style="height: 100px; width: 100px; opacity: 0"/><!-- 用于回顯圖片 --><img id="image" src="/img/add.svg" /></div><script>const fileInput = document.getElementById("fileInput"); // 獲取上傳文件框const image = document.getElementById("image"); // 獲取回顯圖片框function uploadImage() {const formData = new FormData(); // 創(chuàng)建formData對象,用于存儲要上傳的文件數(shù)據(jù)formData.append("file", fileInput.files[0]); // 將選中的文件添加到formData對象中// 請求接口fetch("http://yikatong.kuxia.top/pc/common/upload", {method: "POST",body: formData, // 請求體是formData對象,其中包含文件數(shù)據(jù)}).then((response) => response.json()) // 服務(wù)器響應(yīng)成功后,解析JSON格式的響應(yīng)數(shù)據(jù).then((data) => {console.log("上傳成功:", data.data.url);// 回顯圖片image.src = "http://yikatong.kuxia.top" + data.data.url;}).catch((error) => {console.error("上傳失敗:", error);});}</script></body>
</html>