1. 程式人生 > >Java web圖片上傳本地預覽,無需後臺寫介面

Java web圖片上傳本地預覽,無需後臺寫介面

前言

本篇部落格為轉載,由於目前很多上傳圖片預覽的外掛都需要Java後臺寫方法先獲取選擇圖片的介面,這個外掛不需要。

下載外掛地址

http://jquery.decadework.com/

原作者部落格地址

http://zhouxiang.decadework.com/article/1000
再次鳴謝該作者,如果作者不想我轉載這篇博文,請告訴我,我會刪除☺

改進外掛有效性驗證提示方式

原來的外掛,當有效性驗證失效時,是使用彈框驗證。這裡我修改成在圖片下方用label顯示報錯資訊,同時在Chrome核心下,重新點選選擇檔案但是不選擇的時候,圖片會消失而不是繼續存在。

我的jsp檔案:

<div class="form-group">
    <label>上傳圖片<span class="star"></span></label>
        <div id="imgdiv">
            <img id="imgShow" width="260" height="260" />
        </div>
</div>
<input type="file" id="up_img" name="logoUrl" class="form-control"
value="" /> <div class="clearfix"></div>

我修改的js檔案主要是_self.Bind方法裡:

  if (this.value) {
   var $upImgBtn = $("#up_img");
   $upImgBtn.next("label.error").remove();   //重新選擇檔案時清空報錯資訊
   if (!RegExp("\.(" + _self.Setting.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
        //alert(_self.Setting.ErrMsg);
//清空圖片 var $imgShow = $("#imgShow"); $imgShow.attr('src',''); //顯示報錯資訊 $upImgBtn.after("<label class='error'>"+ _self.Setting.ErrMsg +"</label>"); $upImgBtn.val(''); this.value = ""; return false; } if (navigator.userAgent.indexOf("MSIE") > -1) {

由於使用了 $ 符號,所以需要引用jQuery.js。

注意

上述程式碼中的class是我專案中自己的css,你們可以改成自己的。
如:

.star {
    color: red;
}