一般系統的實現方式:
- 代碼實現
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>圖片預覽</title>
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<p>
<img class="img" width="100" height="100" id="previewimg">
</p>
<input class="select" type="file" id="picfile">
<script>
$('.select').change(function(e) {
var _URL = window.URL || window.webkitURL;
$("#previewimg").attr("src", _URL.createObjectURL(this.files[0]))
})
</script>
</body>
</html>
- input type="file"就是文件選擇標簽,默認樣式為:
如果不喜歡默認樣式,可以把它設置為透明,然后自己用圖片或元素覆蓋它,這時候他仍然能響應點擊
opacity: 0;
-
multiple="multiple" 屬性可以讓input一次選擇多個文件
-
注冊change監聽或定義onChange方法可以在選擇完圖片后回調,回調中使用files數組屬性來獲取選擇的文件,如果是選擇單文件,files[0]表示選擇的圖片
-
jquery回調中,this會自動指向當前操作的元素,例子中的this和getElementById("picfile")相對,如果要使用jquery方法,可以用$(this)
-
oninput事件在元素值發生變化時立即觸發, onchange在元素失去焦點時觸發,如果是輸入文字,oninput在輸入過程中一直回調(輸入或刪除一個文字就會調用一次),onchange在輸入完成,點擊其他地方調用。
-
createObjectURL把file對象轉為url讓img標簽顯示
android系統的實現
安卓webview系統無法通過input打開系統選擇文件框,必須在原生里面攔截webview事件,選擇完文件,處理相關邏輯(比如上傳文件到oss)后回調到webview
wvmain.setWebChromeClient(new WebChromeClient(){
//For Android >= 5.0
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
uploadPicture();
return true;
}
//For Android >= 4.1
public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
uploadMessage = valueCallback;
uploadPicture();
}
});
- 選擇並處理完文件后,調用Callback(valueCallback 或 filePathCallback)的onReceiveValue方法,webview里的input標簽才會調用onchange
比如以下是選擇完文件后,上傳文件到oss成功后的回調里,如果成功得到oss圖片地址,則調用onReceiveValue方法把圖片的本地uri回傳給webview,失敗或異常情況回傳null給webview
public void successImg(String img_url) {
if (img_url != null){
curPicUrl = img_url;
mHandle.sendEmptyMessage(UPLOAD_SUCESS);
if (uploadMessage != null) {
uploadMessage.onReceiveValue(imageUri);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
uploadMessageAboveL = null;
}
}else{
curPicUrl = "";
mHandle.sendEmptyMessage(UPLOAD_FAIL);
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
}
}
- 如果回傳null給webview,如果input里面之前還沒有文件, input的onchange,oninput方法不會調用,如果之前已經選擇過文件,files對象之前里面有內容,現在內容會變成空,發生了改變,onchange,oninput方法都會調用(先調用oninput),但是files對象的長度為0,可以根據files的長度來做不同的處理,比如:
doChange() {
var file = document.getElementById("fileInput");
if(file.files.length == 0){//清除之前的圖片
document.getElementById("showpic" + i).style.display = "none";
return;
}else{
//顯示圖片預覽
}
}