DIV CSS 佈局教程網

改造 bootstrap-wysiwyg:把圖片上傳改走 Ajax 並即時插入
編輯:關於JavaScript     

為什麼選這個插件

專案需要一個附圖片上傳並能即時預覽的編輯框。比較過幾個方案:UEditor 功能齊全但體積龐大,為了小小的需求引入大量檔案並不划算;easyUI 個人版免費,但這是公司業務專案,用商業授權的框架合適性存疑。由於前端本來就建立在 Bootstrap 之上,最後選了 bootstrap-wysiwyg——夠精簡、夠輕,擴充也容易。

要改的是哪裡

引入並啟用編輯功能很簡單,但要注意:它的圖片上傳是用 File API 實作的。File API 的即時預覽體驗很好, however 真正入庫時,我們希望存的是伺服器上的靜態路徑,而不是字串化的圖片內容。所以這個插件需要小幅改造。

先看圖片按鈕的結構

 <div class="btn-group">
  <a class="btn" title="Insert picture (or just drag & drop)" id="pictureBtn">
    <i class="icon-picture"></i>
  </a>
  <input type="file" data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage" />
</div>

data-role 與 data-target 是 Bootstrap 預定的屬性,屬於版面與事件綁定層面,不用理會。關鍵是第三個屬性 data-edit——Bootstrap 本身並沒有這個約定,但在 bootstrap-wysiwyg.js 裡能找到:

 toolbar.find('input[type=file][data-' + options.commandRole + ']')
  .change(...)

// ...
commandRole: 'edit',

也就是說,data-edit 只是方便選擇器定位而存在的,等同為圖片按鈕掛上監聽。

原本的預覽流程

第一步,監聽器捕到 file input 的 change 事件:

 restoreSelection();
if (this.type === 'file' && this.files && this.files.length > 0) {
  insertFiles(this.files);
}
saveSelection();
this.value = '';

接著進入 insertFiles:

 insertFiles = function (files) {
  editor.focus();
  $.each(files, function (idx, fileInfo) {
    if (/^image\//.test(fileInfo.type)) {
      $.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
        execCommand('insertimage', dataUrl);
      }).fail(function (e) {
        options.fileUploadError("file-reader", e);
      });
    } else {
      options.fileUploadError("unsupported-file-type", fileInfo.type);
    }
  });
}

它用了 jQuery 的 $.Deferred():先呼叫 readFileIntoDataUrl,成功後交給自封裝的 execCommand 插入編輯區。此時插入的其實是一個 <img>,只是 src 被寫成了 data URL。

所以改造方向很明確:監聽觸發後先把檔案上傳,拿到伺服器回傳的 src,再交給 execCommand。

動手改造

ajaxFileUpload 的呼叫形式如下,其中 url 與 fileElementId 是必填:

 $.ajaxFileUpload({
  url: ...,
  secureurl: false,
  fileElementId: ...,
  dataType: "json",
  success: function (obj) { ... },
  error: function () { ... }
});

為了不破壞依賴關係,重寫 ajaxFileUpload 並不可取;但由於控件靠監聽器觸發,也沒辦法直接把參數傳進去。解法是自訂幾個屬性掛在 file input 上:

 <input type="file" id="pictureInput" name="picture"
       data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage"
       action="..." />

id 供 fileElementId 使用,name 是後端取值的依據,action 則是上傳的目標網址。

接著在 bootstrap-wysiwyg.js 裡定義上傳函數:

 var uploadFileToServer = function (id, action, callback) {
  $.ajaxFileUpload({
    url: action,
    secureurl: false,
    fileElementId: id,
    dataType: 'json',
    success: function (obj) {
      if (obj.status) {
        callback(obj.imgsrc);
      } else {
        options.fileUploadError("server-internal-exception", obj.message);
      }
    },
    error: function () {
      options.fileUploadError("upload-failure", "");
    }
  });
};

改寫 insertFiles,把 data URL 那段換成上傳:

 insertFiles = function (files, id, action) {
  editor.focus();
  $.each(files, function (idx, fileInfo) {
    if (/^image\//.test(fileInfo.type)) {
      uploadFileToServer(id, action, function (src) {
        execCommand('insertimage', src);
      });
    } else {
      options.fileUploadError("unsupported-file-type", fileInfo.type);
    }
  });
};

監聽器也要相應調整,才能把屬性值取出來傳下去:

 toolbar.find('input[type=file][data-' + options.commandRole + ']')
  .change(function () {
    restoreSelection();
    if (this.type === 'file' && this.files && this.files.length > 0) {
      insertFiles(this.files, $(this).attr('id'), $(this).attr('action'));
    }
    saveSelection();
    this.value = '';
  });

改完之後要檢查的事

三點提醒:一,ajaxFileUpload.js 必須在控件之前引入,否則會拿到 undefined。二,後端要回傳 JSON,且格式需與 obj.status 與 obj.imgsrc 對應。三,上傳失敗要有出路,範例已把錯誤交給 fileUploadError 處理,記得在初始化時傳入對應的 callback,否則使用者按了按鈕卻毫無反應。

另外,原寫法用 callback 而非 Deferred,是為了降低理解成本。若你已熟悉 Promise,改回 $.Deferred 的鏈式寫法可以讓多檔上傳的錯誤處理更集中,也更容易加入進度提示。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved