input type file
能做這個功能嗎?我看到淘寶,網(wǎng)易,微博移動端頁面都沒有做修改頭像的功能,他們不做還是沒有必要做;認證0級講師
當然能啊 沒看過網(wǎng)頁版貼吧微博么 隨手寫個 Demo
通過 FileReader
讀取文件的 Base64
值并使用 img
標簽顯示預覽
HTML
<label class="upload">
<span>上傳</span>
<input type="file" accept="image/*">
</label>
CSS
/* 隱藏默認的上傳控件 */
input[type=file] {
dispaly: none;
}
/* 自定義上傳按鈕樣式 */
.upload {
...
}
Javascript
document.querySelector('.upload input[type=file]').addEventListener('change', ev => {
const file = ev.target.files[0] // 獲取上傳的第一個文件
ev.target.value = null // 重置 input
const reader = new FileReader()
reader.onload = ev => {
// 讀取文件完畢
const img = document.createElement('img')
img.src = ev.target.result // 文件的 Base64 值
document.body.appendChild(img)
}
console.info(file.name) // 本地文件名
console.info(file.type) // 文件類型 (Content-Type)
console.info(file.size) // 文件大小
reader.readAsDataURL(file)
})
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號